[英]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.