Answer the question
In order to leave comments, you need to log in
How to do object collision check with apple canvas, Javascript?
Hello dear programmers.
How to do object collision check with apple canvas, Javascript ?
please help ))))) game like "Snake"
https://imgur.com/DBetdTj
const canvas = document.getElementById("snake");
const ctx = canvas.getContext("2d");
const fon = new Image();
fon.src = "img/fon.jpg";
const basket = new Image();
basket.src = "img/basket.png";
var apple = new Image();
apple.src = "img/apple.png";
fon.onload = function game(){
update();
render();
}
function update(appleRD, appleSZ, box, snake, x, y, dir, food){
this.appleSZ = {x : 90,y : 90}
this.box = 92;
this.appleRD = {x : 100, y : 100}
this.snake = [];
this.snake[0] = {x : canvas.width / 2, y : canvas.height / 2};
this.food = {x : (Math.floor(Math.random() * 20 + 1)) * this.box, y : (Math.floor(Math.random() * 10 + 1)) * this.box}
this.score = 0;
}
let dir;
document.addEventListener("keydown", control_the_snake);
function control_the_snake(e, update){
if(e.keyCode == 37)
dir = "left"
else if(e.keyCode == 38)
dir = "up"
else if(e.keyCode == 39)
dir = "right"
else if(e.keyCode == 40)
dir = "down"
}
function render(){
ctx.drawImage(fon, 0, 0, 1920, 1080);
ctx.drawImage(basket, 0, 0, this.appleRD.x, this.appleRD.y);
ctx.drawImage(apple, this.food.x, this.food.y, this.appleSZ.x, this.appleSZ.y);
for(let i = 0; i < this.snake.length; i++){
ctx.fillStyle = "#fff";
ctx.fillRect(this.snake[i].x, this.snake[i].y, this.box, this.box);
}
ctx.fillStyle = "#fff";
ctx.font = "70px Arial";
ctx.fillText(this.score, 130, 80);
this.snakeX = this.snake[0].x;
this.snakeY = this.snake[0].y;
if(this.snakeX == this.food.x && this.snakeY == this.food.y){
this.score+=500;
}
this.snake.pop();
if(dir == "left")this.snakeX-= this.box;
if(dir == "right")this.snakeX+= this.box;
if(dir == "up")this.snakeY-= this.box;
if(dir == "down")this.snakeY+= this.box;
let newHead = {
x : snakeX,
y : snakeY
}
this.snake.unshift(newHead);
}
var animation = setInterval(render, 100);
Answer the question
In order to leave comments, you need to log in
Well, if both objects of you are rectangles, then everything is pretty simple. You just need to check that these two rectangles do not intersect. This condition is written
function isColission(block1, block2) {
return !(block2.x > (block1.x + block1.width) || // проверяем, что позиция блока 2 больше позиции правого края блока 1
(block2.x + block2.width) < block1.x || // проверяем, что позиция правого края блока 2 меньше позиции левого края блока 1
block2.y > (block1.y + block1.height) || // и также по Y
(block2.y + block2.height) < block1.y));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question