web-dev-qa-db-ja.com

キーボードコントロールを使用したキャンバスゲームでのスムーズなキャラクターの動き

キャンバスとJavaScriptを使用して、横スクロールの無限の宇宙をテーマにしたゲームを作成しています。上下の矢印だけで宇宙船を操縦しているのですが、キーを離したときに船が止まらないように、なんらかの動きの緩和を実装したいと思います。周りを見回しても何も見つかりませんでしたが、自分の試みがうまくいきませんでした。これは私が試したものです。

Jet.prototype.checkDirection = function () {
if (this.isUpKey) {
    this.drawY -= this.speed;
    if (this.speed < 5) {
        this.speed += 0.1;
    }
}
if (this.isDownKey) {
    this.drawY += this.speed;
    if (this.speed < 5) {
        this.speed += 0.1;
    }
}
if (!this.isUpKey) {
    if (!this.isDownKey) {
        if (this.speed >= 0) {
            this.drawY -= this.speed;
            this.speed -= 1;
        }
    }
}
if (!this.isDownKey) {
    if (!this.isUpKey) {
        if (this.speed >= 0) {
            this.drawY += this.speed;
            this.speed -= 1;
        }
    }
}
13
Joe Taylor

摩擦を加えたいだけです。そのかなり簡単です。次のようなことができます。

this.speed*=0.98;

値が小さいほど(0.8、0.5など)、速度が速くなります。

私はあなたが動き回ることができ、徐々に遅くなるデモを提供しました。先に進んで値を試して、それがどのように影響するかを確認してください。

ライブデモ

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = canvas.height = 300;

var x = 150,  //initial x
    y = 150,  // initial y
    velY = 0,
    velX = 0,
    speed = 2, // max speed
    friction = 0.98, // friction
    keys = [];

function update() {
    requestAnimationFrame(update);

    // check the keys and do the movement.
    if (keys[38]) {
        if (velY > -speed) {
            velY--;
        }
    }

    if (keys[40]) {
        if (velY < speed) {
            velY++;
        }
    }
    if (keys[39]) {
        if (velX < speed) {
            velX++;
        }
    }
    if (keys[37]) {
        if (velX > -speed) {
            velX--;
        }
    }

    // apply some friction to y velocity.
    velY *= friction;
    y += velY;

    // apply some friction to x velocity.
    velX *= friction;
    x += velX;

    // bounds checking
    if (x >= 295) {
        x = 295;
    } else if (x <= 5) {
        x = 5;
    }

    if (y > 295) {
        y = 295;
    } else if (y <= 5) {
        y = 5;
    }

    // do the drawing
    ctx.clearRect(0, 0, 300, 300);
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, Math.PI * 2);
    ctx.fill();
}

update();

// key events
document.body.addEventListener("keydown", function (e) {
    keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
    keys[e.keyCode] = false;
});
26
Loktar

私がやろうとしていることは、キーアップで船を止めないことだと思います。少し遅くする関数を持っているだけで、setIntervalでこの関数を任意の間隔で呼び出して、希望の効果が得られたら、船の速度がゼロになります。 clearIntervalを呼び出す

したがって、キーアップでは、基本的にsetInterval(slowShip、500)を設定します。

2
Tutan Ramen

すべてのフレームで継続的に速度を下げてみることができます

if(!playerUp && !playerDown && moveSpeed > 0){
    moveSpeed--;
}
1
john guthrie