碰撞检测p5.js [英] Colision detection p5.js
问题描述
仅尝试在p5.js中制作一个简单的Pong游戏.我最近刚接触JavaScript,无法弄清球和球棒之间的碰撞检测.我尝试了几种方法,但是它基本上只是停止了我的代码的运行..等..希望有任何帮助!
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!
这是我的源代码:
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){
您可能还需要阅读该教程的与移动对象的碰撞检测部分.它是为处理而编写的,但是所有内容也适用于P5.js.
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.
如果您无法正常工作,请从一个更基本的草图开始,该草图仅显示两个硬编码的矩形.当它们不碰撞时,使其变为红色.然后从那里继续前进.很难回答一般的我该怎么做"类型的问题,因此,如果发布特定的我尝试过X,期望Y,但是却得到了Z"类型的问题,那么您的运气会更好.祝你好运.
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.
这篇关于碰撞检测p5.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!