簡體   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