[英]Resetting a class parameter upon new instance of that class: JS ES6
我正在创建一个游戏,每次玩家进入一个新的“房间”时都会重新绘制画布。 虽然大部分功能都在那里,但我在播放器方面遇到了一些麻烦......虽然我的房间绘制课程 Room 的其余部分在没有参考前一个房间的情况下被重置和重新初始化,但播放器方块会继续到下一个屏幕并留在同一个地方。
我的用户类:
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);
};
您可以在此处在 CodePen 上看到这一点。 相关的行是 10、53、185 和 232。
new to the canvas element, so I'm sure I'm making a rookie mistake in here somewhere, but I can't seem to spot it.我对 JS陌生,对 canvas 元素也陌生,所以我确定我在这里的某个地方犯了一个新手错误,但我似乎无法发现它。
在用新变量覆盖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));
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.