Colision detection p5.js

just trying to make a simple pong game in p5.js. I have very recently gotten into JavaScript and can't manage to figure out collision detection between the ball and the bat. I have tried a few ways of doing it but it mostly just stopped my code from running.. etc.. would love any help!

Here is my source code:

function setup() {     
  createCanvas(750, 750);

var x = 50;    
var y = 50;    
var direction = 5;    
var arrow = 0;    
var ball;    
var bat;

function draw() {     
  fill ('white');    
  ball = ellipse (x, y, 50, 50);    
  x = x + direction;

  if (x > width - 25){    
    direction = -5;    

  if (x < 25) {    
    direction = 5;    


  if (keyIsDown(RIGHT_ARROW)){    
    arrow += 7;    

  if (keyIsDown(LEFT_ARROW)){    
    arrow += -7;    

  fill ('black');    
  bat = rect(arrow, 600, 150, 15);



Your question is pretty broad, but basically what you want to do is imagine a "bounding rectangle" around the ball, and then use rectangle-rectangle collision to check whether the ball is colliding with a paddle. If it is, "bounce" the ball by multiplying its horizontal speed by -1.

I wrote a tutorial on collision detection available here, but the basic if statement looks like this:

if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){

You also might want to read the Collision Detection with Moving Objects section of that tutorial. It's written for Processing, but everything applies to P5.js as well.

If you're having trouble getting it working, then please start over with a more basic sketch that just shows two hard-coded rectangles. Make them turn red when they're not colliding. Then work your way up from there. It's hard to answer general "how do I do this" type questions, so you'll have much better luck if you post a specific "I tried X, expected Y, but got Z instead" type question. Good luck.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.