Hit Detection of two objects.

I'm trying to find a method, for finding wether two objects have collided, i.e they have the same location. However my For loop won't work as it doesn't even enter it. One object, Snake, has an x and y location, the food or 'apples' also have an x and y location. When they = eachother, it should log ''Collision''. I'll post the code below.

var snake;
var apples = [];
function setup() {
  createCanvas(600,600);
  frameRate(10);
  snake = new snake();
  for (var i = 0; i < 20; i++) {
    apples.push(new apple(Math.round(random(600) / 10) * 10,Math.round(random(600) / 10) * 10));
  } //generates apples 
}

function draw() {
  background(51);
  snake.update();
  snake.show();
  
  for (var i = 0; i < 20; i++) {
    apples[i].show();
  }
}

function keyPressed() {
  if (keyCode === 87) {
    snake.dir(0,-10);
  } 
  else if (keyCode === 83){
    snake.dir(0,10);
  } 
  else if (keyCode === 65){
    snake.dir(-10,0);}
    
    else if (keyCode === 68) {
    snake.dir(10,0);
    }
  }

function snake() {
  this.x = 300;
  this.y = 300;
  this.xspeed = 0;
  this.yspeed = 0;
  
  this.update = function(){
    this.x = this.x + this.xspeed;
    this.y = this.y + this.yspeed;
    Math.ceil(this.x / 10) * 10;
    Math.ceil(this.y / 10) * 10;
    
    for (var i = 0; i == apples.length - 1; i++){
      if (this.x == apples[i].x && this.y == apples[i].y){
        console.log ("collision");
      }
    }
  }

  this.show = function() {
    fill(255);
    rect(this.x,this.y,10,10);
  }
  
  this.dir = function(x,y){
    this.xspeed = x;
    this.yspeed = y;
    
  }
}

function apple(x,y) {
  this.x = x;
  this.y = y;
  
  this.show = function() {
    fill(255);
    rect(this.x,this.y,10,10);
  }
}
Tagged:

Answers

Sign In or Register to comment.