繁体   English   中英

JavaScript p5.js:对象对齐

[英]JavaScript p5.js: Object Alignment

嗨,我现在正在制作蛇游戏,但我遇到的问题是我的食物与蛇不对齐,所以我无法让蛇吃掉它,没有错误信息也无法使蛇起作用,请解释在哪里我弄错了,我怎么能使它被排列和食用。

这是我的代码:

我的食物:

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();
  }
}

查看以下行:

if (this.x === food.x && this.y === food.y)

您只在检查蛇是否与食物完美对齐。 就像您已经发现的那样,这几乎永远不会发生,因为它需要像素完美的精度。

相反,您想检测蛇是否正在与食物碰撞。 您可以使用冲突检测执行此操作。 Google是您的朋友,但是检查两个矩形的通用算法是:

if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
  //rectangles are colliding
}

无耻的自我促进:我在此处编写了有关碰撞检测的教程。 它用于处理,但是P5.js中的所有内容都相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM