我正在创建一个游戏,每当玩家进入一个新的“房间”时重绘画布。虽然大部分功能都在那里,但我在播放器上遇到了一些麻烦...虽然我的房间绘图课室的其余部分被重置并重新初始化而没有参考前一个房间,但是播放器方块会进入下一个屏幕并留在同一个地方。
我的用户类:
class User {
constructor(user, x, y, ctx) {
for (let metric in user) { this[metric] = user[metric]; }
this.initialX = x;
this.initialY = y;
this.ctx = ctx;
this.move = this.move.bind(this);
//// various other constructor things...
}
//// various other methods
move(e) {
//// motion description
if (this.y - 5 <= 0 {
init(theRoom.connectingRooms[0], this.x, 550) ///// should create a new box at the last player-x position and y-position 550
}
}
}
我的房间课程:
class Room {
constructor(canv, room, player) {
for (let key in canv) { this[key] = canv[key]; }
for (let attr in room) { this[attr] = room[attr]; }
this.drawWalls();
this.player = player; /// adding player to room
} /// end of constructor
////methods, nothing that affects player
}
初始化器:
let init = function init(room, x, y) {
canv = document.getElementById('canvas');
canvas = new CanvasState(canv);
player = new User(user, x, y, canvas.ctx); //// it's remembering the last player I set instead of removing the old one & creating a new one
theRoom = new Room(canvas, room, player);
window.addEventListener('keydown', theRoom.player.move);
window.addEventListener('keyup', theRoom.typeInput);
};
您可以看到此on CodePen here。相关的行是10,53,185和&amp; 232。
我是JS的新手,非常画布元素的新手,所以我确定我在这里某个地方犯了一个新手的错误,但我似乎无法发现它
答案 0 :(得分:1)
在使用新变量覆盖player
变量之前,您需要从window
中删除密钥处理程序。那些仍然引用旧玩家对象的方法,因此每次移动时都会绘制它们。
您可以使用
function init(room, x, y) {
canv = document.getElementById('canvas');
canvas = new CanvasState(canv);
if (player != null)
window.removeEventListener('keydown', player.move);
player = new User(user, x, y, canvas.ctx);
window.addEventListener('keydown', player.move);
if (theRoom != null)
window.removeEventListener('keyup', theRoom.typeInput);
theRoom = new Room(canvas, room, player);
window.addEventListener('keyup', theRoom.typeInput);
}
另一种方法是只注册一个调用当前对象的相应方法的回调(这样你也不需要.bind
):
function init(room, x, y) {
canv = document.getElementById('canvas');
canvas = new CanvasState(canv);
player = new User(user, x, y, canvas.ctx);
theRoom = new Room(canvas, room, player);
}
window.onload = function() {
init(castleCourtyard, 350, 100);
window.addEventListener('keyup', e => theRoom.typeInput(e));
window.addEventListener('keydown', e => player.move(e));
};