使用键盘控件在画布游戏中平滑角色移动

Joe*_*lor 13 javascript canvas game-physics easing

我正在使用canvas和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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Lok*_*tar 26

你只想施加一些摩擦力.它非常简单.您可以执行以下操作.

this.speed*=0.98;
Run Code Online (Sandbox Code Playgroud)

值越低(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;
});
Run Code Online (Sandbox Code Playgroud)

  • 太棒了,这正是我一直在寻找的感谢! (2认同)
  • 太棒了!正是我所需要的。极大地简化了我的代码。 (2认同)