From eb0466083b9dfa3b8a16fc3b390051c8bb458dfc Mon Sep 17 00:00:00 2001 From: Mees Roelofsz Date: Fri, 24 Nov 2023 13:30:10 +0100 Subject: [PATCH] added collision between circle and square --- web/game.js | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/web/game.js b/web/game.js index f072c24..c164d9b 100644 --- a/web/game.js +++ b/web/game.js @@ -1,15 +1,19 @@ -size = 10; +const size = 10; radius = size/2; cirX = 500 cirY = 300; -xmax = 1000; -ymax = 600; +const width = 1000; +const height = 600; speed = 3; +squareX = 100; +squareY = 100; +const squareSize = 100; + // the function setup() is called once when the page is loaded function setup() { // create a canvas element and append it to the body - createCanvas(xmax, ymax); - frameRate(1200); + createCanvas(width, height); + frameRate(120); // disable the outline of shapes noStroke(); } @@ -18,19 +22,27 @@ function keyPressed() { if (keyIsDown(LEFT_ARROW) && cirX > 0+radius) { cirX -= speed; } - if (keyIsDown(RIGHT_ARROW) && cirX < xmax-radius) { + if (keyIsDown(RIGHT_ARROW) && cirX < width-radius) { cirX += speed; } if (keyIsDown(UP_ARROW) && cirY > 0+radius) { cirY -= speed; } - if (keyIsDown(DOWN_ARROW) && cirY < ymax-radius) { + if (keyIsDown(DOWN_ARROW) && cirY < height-radius) { cirY += speed; } } -function collision() { +function object_collision() { + var squareCenterX = squareX + squareSize / 2; + var squareCenterY = squareY + squareSize / 2; + var distance = dist(cirX, cirY, squareCenterX, squareCenterY); + + if (distance < squareSize / 2 + radius) { + squareX = random(0, width - squareSize); + squareY = random(0, height - squareSize); + } } // the function draw() is called every frame @@ -41,6 +53,7 @@ function draw() { // draw a circle at the mouse position - circle(constrain(cirX,0+radius,xmax-radius), constrain(cirY,0+radius,ymax-radius), size); - square(100,100,100,10); + circle(constrain(cirX,0+radius,width-radius), constrain(cirY,0+radius,height-radius), size); + square(squareX,squareY,squareSize); + object_collision(); } \ No newline at end of file