#javascript #typescript
Вопрос:
Я пытаюсь создать игру с машинописным текстом, и я пытаюсь переместить кошку с помощью стрелок вверх, вниз, влево и вправо на клавиатуре. Теперь я могу только двигать кошку вверх и вниз. Кто-нибудь знает, что не так с моим кодом и почему я не могу перемещать его влево и вправо? Что я сделал, так это использовал прослушиватель событий и событий, чтобы посмотреть, нажата клавиша или нет. Если это так, то в тех случаях, когда вы можете видеть, в каком случае это так. Я придал ему как вертикальную, так и горизонтальную скорость. Я чувствую, что либо чего-то не хватает, либо я сделал что-то не так. Я не получаю никаких ошибок.
export class Cat{
// Fields
private x : number = 0
private y : number = 0
private div: HTMLElement
private verticalSpeed : number = 0
private horizontalSpeed : number = 0
public getBoundingRect() : DOMRect {
return this.div.getBoundingClientRect()
}
constructor(tagName: string) {
console.log("Cat was created!")
// Add the event listeners to the window for the keyboard events
window.addEventListener("keydown", (e: KeyboardEvent) => this.onKeyDown(e))
window.addEventListener("keyup", (e: KeyboardEvent) => this.onKeyUp(e))
this.create()
this.y = Math.floor(Math.random() * (window.innerWidth - this.div.clientWidth))
this.y = Math.floor(Math.random() * (window.innerHeight - this.div.clientHeight))
this.x = Math.floor(Math.random() * (window.innerWidth - this.div.clientWidth))
this.x = Math.floor(Math.random() * (window.innerHeight - this.div.clientHeight))
}
private create() : void {
this.div = document.createElement("cat")
document.body.appendChild(this.div)
}
public update() : void {
// Add the vertical speed to the y-value
this.y = this.verticalSpeed
this.x = this.horizontalSpeed
// Draw the shark on the right coordinate (x, y)
this.div.style.transform = `translate(${this.x}px, ${this.y}px)`
}
private onKeyDown(e: KeyboardEvent): void {
// log the keyboard
// console.log(e.key)
// Check if the key in the event (e.key) matches the desired input
switch (e.key) {
// When the "ArrowUp" key is pressed
case "ArrowUp":
// Give the vertical speed a negative value
this.verticalSpeed = -5
break
// When the "ArrowDown" key is pressed
case "ArrowDown":
// Give the vertical speed a positive value
this.verticalSpeed = 5
break
case "ArrowLeft":
// Give the horizontal speed a neegative value
this.horizontalSpeed = -5
break
case "ArrowRight":
// Give the horizontal speed a positive value
this.horizontalSpeed = -5
break
}
}
private onKeyUp(e: KeyboardEvent): void {
// Check if ArrowUp or ArrowDown key has been released
if(e.key == "ArrowUp" || e.key == "ArrowDown" || e.key == "ArrowLeft" || e.key == "ArrowRight" ){
// Make the vertical speed 0
this.verticalSpeed = 0
//make the horizontal speed 0
this.horizontalSpeed = 0
}
}
}
Комментарии:
1.
case "ArrowRight": // Give the vertical speed a positive value this.horizontalSpeed = -5
неправильное копирование/вставка?2. извините, что я ошибся, я изменил его