I'm trying to code a snake game (I'm kinda new to all this) and I'm currently stuck on this collision function. I tried to follow instructions on here Detecting collision of rectangle with circle but I'm still quite confused. For example the coordinates X and Y of the circle and rectangle are always changing. Furthermore, I am not sure how to call my circle and rectangle elements in my gameboard object where I am writing my collision dectection either... snakeHead is my circle and foodElement my rectangle.
Here's my code... Sorry if I didn't express myself in a super clear manner hence the confusion...
function collision(snakeHead, FoodElement) {
var snakeHead = {x, y, r}; //r is radian
var FoodElement = {x, y, w, h}; //w: width, h: height
var distX = Math.abs(snakeHead.x - FoodElement.y - FoodElement.w / 2);
var distY = Math.abs(snakeHead.x - FoodElement.y - FoodElement.h /2);
if (distX > (FoodElement.w/2 + circle.r)) {return false;}
if (disY > (FoodElement.h/2 + circle.r)) {return false;}
if (distX <= (FoodElement.w/2)) { return true; }
if (distY <= (FoodElement.h/2)) { return true; }
var dx = distX - FoodElement.w/2;
var dy = distY - FoodElement.h/2;
return (dx*dx+dy*dy<=(snakeHead.r*snakeHead.r));
console.log("IMPACT"); }
Some lines seems to be incorrect, here is my correction (I supposed snakeHead position is the center of the head):
var distX = Math.abs(snakeHead.x - FoodElement.x - FoodElement.w / 2);
var distY = Math.abs(snakeHead.y - FoodElement.y - FoodElement.h / 2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.