繁体   English   中英

我需要在画布上移动播放器的帮助

[英]i need help moving my player in the canvas

我无法使图像在画布中移动。 尝试了很多事情而失败了,请帮助

var canvas = document.getElementById("mainCanvas");
canvas.width  = document.body.clientWidth;
canvas.height = document.body.clientHeight;
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";

从这里开始

var player = function(img){
    x=10,
    y=10,
    width=20,
    height=20

}

添加玩家

window.addEventListener("keydown", function(e){
    keys[e.keyCode] = true;
}, false);

window.addEventListener("keyup", function(e){
    delete keys[e.keyCode];
}, false);

function game(){
    update();
    render();
}

function update(){
    if(keys[37]) player.y--;
    if(keys[38]) player.y++;
    if(keys[39]) player.x--;
    if(keys[40]) player.x++;

};

我需要知道如何让玩家移动

我建议更改您的代码逻辑。 首先,使用requestAnimationFrame()注册要触发的方法,该方法仅在需要时才自动渲染/更新画布。 此处阅读基本详细信息。 我不知道您的逻辑是如何实现的,发布的源代码还很不完整,但是建议您将var player更改为object而不是function(以便player.x ++可以使用):

function render() {
  //your render code here
  player1.draw();
  requestAnimationFrame(render);
}

function Player(img){
  this.x = 10;
  this.y = 10;
  this.height = 20;
  this.width = 20;
  this.img = img;
}

Player.prototype.draw = function() {
  canvas.drawImage(this.img);
};

//create instance of Player
player1 = new Player(handleToYourPlayerImage);

// start it
requestAnimationFrame(render);

(不要忘记在上面添加键盘处理代码。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM