[英]How can I make snake game detect collision with its tail?
我目前正在使用 2d 畫布編寫 JavaScript Snake 游戲時遇到碰撞檢測問題。 這對我來說是相當新的。 對邊緣的碰撞檢測按預期工作。 但是,當涉及到檢測蛇是否撞到自己時,我遇到了麻煩。
我一直在尋找其他類似的主題,但沒有發現它們直接適用於我的案例。
您將在下面找到游戲循環、蛇對象和碰撞檢測功能。 任何關於為什么當蛇撞到自己時碰撞檢測不會觸發的指針,將不勝感激。
// Game loop
function GameLoop() {
map.DrawMap();
map.DrawSnake(snake);
map.DrawFood(food);
RenderScore();
snake.IncrementTail();
snake.DirectionChange(map);
if (snake.EatFood(food, map)){
IncrementScore();
snake.maxLength++;
food = Food.GetRandomFood(map);
}
if (!snake.isOutOfBounds(map) && !snake.IsTouchingItself()) {
setTimeout(GameLoop, REFRESH_RATE);
}
}
在 GameLoop 結束時,我的游戲應該檢查snake.isOutOfBounds(map)
和snake.IsTouchingItself()
。 第二,沒有按預期觸發。
// Snake object
export class Snake {
constructor(map) {
this.positions = [{
x: map.GetBlockSize() * 5,
y: map.GetBlockSize() * 5
},
{
x: map.GetBlockSize() * 4,
y: map.GetBlockSize() * 5
},
{
x: map.GetBlockSize() * 3,
y: map.GetBlockSize() * 5
}],
this.colorBody = '#45b6fe',
this.colorHead = '#0e2433',
this.d,
this.maxLength = 3,
this.moves = 0
}
isOutOfBounds(map){
if ( this.positions[0].x >= map.width
|| this.positions[0].x < 0
|| this.positions[0].y >= map.height
|| this.positions[0].y < 0
){
console.log('Snake is attempting to flee.');
return true;
}
}
EatFood(food, map){
if ( this.positions[0].x == food.x
&& this.positions[0].y == food.y){
return true;
} else {
return false;
}
}
IncrementTail(){
var position = { x: this.positions[0].x,
y: this.positions[0].y };
this.positions.unshift(position);
if (this.positions.length > this.maxLength){
this.positions.pop()
}
}
IsTouchingItself(){
for (var i = 2; i < this.positions.length; i++){
if (this.positions[0].x === this.positions[i].x
&& this.positions[0].y === this.positions[i].y){
console.log('Snake is touching itself!');
return true;
} else {
console.log('Snake is well raised.');
return false;
}
}
}
}
嘗試檢查頭部的位置是否與身體部位的位置相匹配。
//I guess the snake's head is the first element in this.positions (index 0)
isSnakeDead() {
//Creating the variables for simplicity
let headX = this.positions[0].x;
let headY = this.positions[0].y;
//The for loop starts from 1 because the head is index 0
//and you don't want to check if the head collides with itself
for (let i = 1; i < this.positions.length; ++i) {
//Another variables for simplicity
let currentX = this.positions[i].x;
let currentY = this.positions[i].y;
if (headX === currentX && headY === currentY) {
//The head collides with the current body part
return true;
}
}
//If the function reaches here then
//the head does not collide with any of the other parts
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.