画布中对象之间的碰撞检查始终在正面

时间:2018-08-21 05:42:27

标签: javascript html5-canvas collision-detection

为什么我的Snake和SnakeFood对象之间的碰撞检测不起作用?

这是我的Snake构造函数:

 class Snake {
   constructor() {
    this.x = 10;
    this.y = 10;
    this.xspeed = 1;
    this.yspeed = 0;
    this.scl = 20;
    this.height = this.scl;
    this.width = this.scl;
    //eatenfood technically is 1 for the snake head.
    this.size = 0;
    this.tail = [];
  }

  direction(x, y) {
    this.xspeed = x;
    this.yspeed = y;
  }

  update() {
    if (this.tail.length === this.size) {
      for (let i = 0; i < this.tail.length - 1; i++) {
        this.tail[i] = this.tail[i + 1];
      }
    }
    this.tail[this.size -1] = { x: this.x, y: this.y };

    this.x = this.x + this.xspeed;
    this.y = this.y + this.yspeed;
  }

  show(ctx) {
    ctx.fillStyle = '#00b273';
    ctx.fillRect(this.x * this.scl, this.y * this.scl, this.scl, this.scl);
  }
}

这是我的SnakeFood构造函数:

class SnakeFood {
  constructor(width, height) {
    this.x = 15;
    this.y = 15;
    this.width = 20;
    this.height = 20;
    //type, color, size
  }

  show(ctx) {
    ctx.fillStyle = 'red';
    ctx.fillRect(this.x * 20, this.y * 20, this.width + 10, this.height + 10);
  }
}

这就是我检查另一个文件中的冲突的方式。

function foodCollision() {
  let rect1 = snake;
  let rect2 = food;

  if ((rect1.x < (rect2.x + rect2.width)) &&
   ((rect1.x + rect1.width) > rect2.x) &&
   (rect1.y < (rect2.y + rect2.height)) &&
   ((rect1.y + rect1.height) > rect2.y)) {
    console.log('collision!');
  } else {
    console.log('no collision');
  } 
 }

碰撞检查总是打印出“碰撞!”即使当蛇不在snakeFood对象附近时,我也无法实现MDN的矩形碰撞检测。

这是我在主文件中绘制对象的方式:

function draw() {
  //draw canvas
  ctx.fillStyle = 'white';
  ctx.fillRect(0, 0, width, height);
  if (wallCollision(canvas.width, canvas.height)) {
    playing = !playing;
    console.log('collided with walls', snake.x, 'x', snake.y, 'y');
  }
  food.show(ctx);
  snake.show(ctx);
  snake.update();

  if (playing) {
    setTimeout(draw, 1000/10);
  }
}

我的进口货:

import Snake from './snake.js';
import SnakeFood from './snakeFood.js';

const canvas = document.getElementById('snake_canvas');
const ctx = canvas.getContext("2d");
const width = canvas.width;
const height = canvas.height;
const snake = new Snake();
const food = new SnakeFood(width, height);
let playing = true;

0 个答案:

没有答案