您好我现在正在制作一个蛇游戏,我有一个问题,我的食物与我的蛇不对齐所以我不能让我的蛇吃它,没有错误消息只是可以&#39为了让它工作,请解释我哪里出错了,以及我如何让它对齐和吃掉。
这是我的代码:
我的食物:
function columns()
{
return floor(width / scl);
}
function rows()
{
return floor(height / scl);
}
function randomPlaceFood()
{
return createVector(floor(random(columns())), floor(random(rows())));
}
function Food()
{
this.vector = randomPlaceFood().mult(scl);
this.x = random(0, 700);
this.y = random(0, 700);
this.updateFood = function()
{
this.vector = randomPlaceFood().mult(scl);
}
this.showFood = function()
{
fill(255, 0, 10);
rect(this.x, this.y, scl, scl);
}
}
我的蛇:
function Snake()
{
this.x = 0;
this.y = 0;
this.xspeed = 0;
this.yspeed = 0;
this.updateSnake = function()
{
this.x = this.x + this.xspeed * scl;
this.y = this.y + this.yspeed * scl;
this.x = constrain(this.x, 0, width - scl);
this.y = constrain(this.y, 0, height - scl);
}
this.showSnake = function()
{
fill(255);
rect(this.x, this.y, scl, scl);
}
this.direction = function(x, y)
{
this.xspeed = x;
this.yspeed = y;
}
this.eatFood = function()
{
if (this.x === food.x && this.y === food.y)
{
randomPlaceFood();
}else
{
randomPlaceFood();
}
}
this.keyPressed = function()
{
if (keyCode === 87)
{
snake.direction(0, -1);
} else if (keyCode === 83)
{
snake.direction(0, 1);
} else if (keyCode === 68)
{
snake.direction(1, 0);
} else if (keyCode === 65)
{
snake.direction(-1, 0);
}
}
}
主文件:
var snake;
var scl = 20;
var food;
function setup()
{
//Sets the Canvas
createCanvas(700, 700);
//Creates a new object using the variable snake
snake = new Snake();
food = new Food();
frameRate(10);
}
function draw()
{
//Sets the Background, number implies the colour
background(40);
//Adds all the values set within the function to the snake
snake.updateSnake();
snake.showSnake();
snake.keyPressed();
food.showFood();
food.updateFood();
if(snake.eatFood())
{
randomPlaceFood();
}
}
答案 0 :(得分:0)
查看此行:
if (this.x === food.x && this.y === food.y)
您只是检查蛇是否与食物完全对齐。就像你已经发现的那样,这几乎从未发生过,因为它需要像素完美的精度。
相反,您想要检测蛇是否与食物发生碰撞。你使用碰撞检测来做到这一点。谷歌是你的朋友,但检查两个矩形的一般算法是:
if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
//rectangles are colliding
}
无耻的自我推销:我写了一篇关于碰撞检测的教程here。它适用于Processing,但P5.js中的所有内容都是相同的。