Javascript 用于移动对象的基本键盘功能
我无法找出我的代码有什么问题。我有另一个例子,我可以开始工作,但它没有使用构造函数对象,而这一个。这是我能想到的唯一不同之处。我在很多方面都做了调整,但是运气不好。请帮助我理解为什么它不起作用Javascript 用于移动对象的基本键盘功能,javascript,addeventlistener,keyboard-events,Javascript,Addeventlistener,Keyboard Events,我无法找出我的代码有什么问题。我有另一个例子,我可以开始工作,但它没有使用构造函数对象,而这一个。这是我能想到的唯一不同之处。我在很多方面都做了调整,但是运气不好。请帮助我理解为什么它不起作用 function newGame() { let Player, Controller; let context = document.getElementById("canvas").getContext("2d"); //Player Playe
function newGame() {
let Player, Controller;
let context = document.getElementById("canvas").getContext("2d");
//Player
Player = function (x, y, width, height) {
this.width = width,
this.height = height,
this.x = x,
this.y = y,
this.xVelocity = 0;
this.yVelocity = 0;
this.update = function () {
context.fillStyle = "red";
context.fillRect(this.x + this.xVelocity, this.y + this.yVelocity, this.width, this.height);
};
};
let player1 = new Player(200, 200, 25, 25);
let playerUpdate = function () {
player1.update();
};
//Controller
Controller = function() {
this.right = false;
this.left = false;
this.keyDownUp = function(e) {
let keyInput = (e.type == "keydown") ? true : false;
console.log(keyInput)
switch (e.keyCode) {
case 37:
this.left = keyInput;
break;
case 39:
this.right = keyInput;
}
}
};
let loop = function () {
if (Controller.left) {
player1.xVelocity += 10;
};
playerUpdate();
};
window.requestAnimationFrame(loop);
window.addEventListener("keydown", Controller.keyDownUp);
window.addEventListener("keyup", Controller.keyDownUp);
}
newGame();
您的
循环只运行一次<代码>请求动画帧(循环)
类似于setTimeout
您需要为每一帧调用它。添加行requestAnimationFrame(循环)代码>位于函数循环的底部
范例
function loop() {
if (Controller.left) {
player1.xVelocity += 10;
}
playerUpdate();
requestAnimationFrame(loop); // get next frame
};
requestAnimationFrame(loop); // start animation
重新评论
代码乱七八糟,我不确定你的部分意图
我把它改写如下,猜测你的意图
(()=>{
功能播放器(x、y、宽度、高度){
this.width=宽度,
this.height=高度,
这个,x=x,
这个。y=y,
该值为0.vx=0;
这是0.vy=0;
}
Player.prototype={
更新(){
this.vx=控制器.left?-10:0;
this.vx=controller.right?10:this.vx;
this.x+=this.vx;
this.y+=this.vy;
this.x=(this.x+ctx.canvas.width)%ctx.canvas.width;
},
画(){
ctx.fillStyle=“红色”;
ctx.fillRect(this.x,this.y,this.width,this.height);
}
}
函数控制器(){
this.right=false;
this.left=false;
addEventListener(“keydown”,keyEvent.bind(this));
addEventListener(“keyup”,keyEvent.bind(this));
功能键事件(e){
如果(e.code==“ArrowRight”){this.right=e.type===“keydown”}
如果(e.code==“ArrowLeft”){this.left=e.type==“keydown”}
}
}
函数循环(){
clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
player.update();
player.draw();
请求动画帧(循环);
};
const ctx=document.getElementById(“画布”).getContext(“2d”);
const controller=新控制器();
常量玩家=新玩家(200、175、25、25);
请求动画帧(循环);
})();代码>
响应的Thx。我把它添加到循环中,但仍然没有运气。我还缺什么吗?这里的代码笔,如果它有帮助的话,它似乎也像它应该的动画功能工程。如果我将循环中的Controller.left
更改为true
,它将设置动画。我想问题在于切换keyCode使控制器。控制器功能中的left
切换为true。@Justin我已经更新了答案,这可能会有所帮助。我想我更接近了。我意识到我从未创建过Controller新Controller
的实例。现在我有了它并通过侦听器事件进行了更新,我得到了console.log中切换为true的Controller.left
。不过还是没有动静。谢谢你的帮助!我正处于js的婴儿期。刚刚完成FCC,我渴望了解更多。