15

キャンバスと 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;
        }
    }
}
4

3 に答える 3

28

摩擦を適用したいだけです。とても簡単です。次のようなことができます。

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;
});
于 2013-03-11T19:43:12.970 に答える
2

私がすることは、キーアップで船を止めないことだと思います。少し遅くする関数を用意してから、setIntervalでこの関数を任意の間隔で呼び出して、船の速度がゼロになると、 clearInterval を呼び出す

したがって、keyup u では基本的に setInterval(slowShip, 500) をセットアップします

于 2013-03-11T17:29:38.813 に答える