Colision detection p5.js

若如初见. 提交于 2020-01-11 11:55:10

问题


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() {     
  background(220);    
  fill ('white');    
  ball = ellipse (x, y, 50, 50);    
  x = x + direction;

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

  if (x < 25) {    
    direction = 5;    
  }

  x++;    
  y++;

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

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

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

回答1:


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.



来源:https://stackoverflow.com/questions/45650655/colision-detection-p5-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!