JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了javascript – 使用键盘控件在画布游戏中平滑的人物运动大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
对,我正在使用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;
        }
    }
}

解决方法

你只想施加一些摩擦.它很容易你可以做如下的事情.
this.speed*=0.98;

值越低(0.8,0.5等)越快,你会减速.

我提供了一个演示,您可以在其中移动,并将逐渐减慢.继续玩这个价值,看看它是如何影响的.

Live Demo

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,300,300);
    ctx.beginPath();
    ctx.arc(x,y,5,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;
});

大佬总结

以上是大佬教程为你收集整理的javascript – 使用键盘控件在画布游戏中平滑的人物运动全部内容,希望文章能够帮你解决javascript – 使用键盘控件在画布游戏中平滑的人物运动所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。