gpt4 book ai didi

javascript - 制作 JavaScript 游戏的难度

转载 作者:行者123 更新时间:2023-12-03 08:46:43 24 4
gpt4 key购买 nike

我正在为一个学校项目制作一个网站并想要实现一个 javascript 游戏,在遇到这个错误之前我已经走了很远。大多数错误我已经能够修复,但这个我无法修复。我的老师也不知道答案所以我希望我能在这里找到一些帮助

这是我的代码

            var player;

function startgame() {
gamearea.start();
playerupdater();
player = new component(30, 30, "blue", 10, 120);
}

var gamearea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateplayer, 50);
},
clear : function(){
console.log(this)
59------> this.canvas.clearRect(0, 0, this.canvas.width, this.canvas.height); <-
}
}

function playerupdatetimeout(){
setTimeout(playerupdater, 25)
}

function playerupdater(){
setInterval(gamearea.clear, 50);
}

function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedx = 0;
this.speedy = 1;
this.x = x;
this.y = y;
this.update = function(){
ctx = gamearea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newpos = function(){
this.x += this.speedx;
this.y += this.speedy;
}
}

function updateplayer(){
player.update();
}

function movup(){
player.speedy -=1;
}

function movdown(){
player.speedy +=1;
}

function movright(){
player.speedx -=1;
}

function movleft(){
player.speedx +=1;
}

控制台指出第 59 行有错误(代码本身已指出)

如果您想自己查看错误,我的网站就在这里: https://jessep2000.github.io./home.html

我用于此页面的所有代码都在此存储库中
https://github.com/Jessep2000/Jessep2000.github.io/tree/master

希望有人知道答案,提前谢谢!

最佳答案

在第 59 行 this.canavas未定义 因为您试图从同一个对象中访问对象键。制作另一个对象,例如:-

let obj ={
clear : function(){
this.gamearea.canavas.clearRect(0, 0, this.canvas.width, this.canvas.height); <-
}
}

当您想使用清除功能时,只需使用:
obj.clear()

关于javascript - 制作 JavaScript 游戏的难度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52096770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com