1 回答

TA貢獻1784條經驗 獲得超7個贊
有幾種方法可以做到這一點。
鑒于您發布的代碼,一種簡單(但不是非常有效)的方法是使用 setInterval() 來運行怪物的邏輯。
一個非常簡單的邏輯可以像這樣工作(偽代碼):
if ( monster.canMoveLeft() && player.x < monster.x ) {
monster.moveLeft()
} else if ( monster.canMoveRight() && player.x > monster.x ) {
monster.moveRight()
} else if ( monster.canMoveUp() && player.y < monster.y ) {
monster.moveUp()
} else if ( monster.canMoveDown() && player.y > monster.y ) {
monster.moveDown()
} else {
// no good choice
// either continue moving in the same direction, or choose a random
// direction if that's not possible
//
// This means you need to keep track of the monster's last direction
}
您還可以檢查水平軸和垂直軸上的距離以確定先行的方向。
項目清單
添加回答
舉報