java如何在处理过程中使弹跳球与矩形阵列碰撞?
我试图让反弹的球在矩形阵列上反弹。我看过其他各种代码,但似乎找不到解决方案。非常感谢您的帮助
基本上,我想让弹跳的球意识到那里有矩形,并且能够跳到矩形上
PVector location; // Location of shape
PVector velocity; // Velocity of shape
PVector gravity; // Gravity acts at the shape's acceleration
PVector upwardForce;
PImage bg;
int radius = 10, directionX = 1, directionY = 0;
float x=20, y=20, speed=0.5;
int xarray[] = new int[20];
int yarray[] = new int[20];
// =========================================================
void setup() {
size(380,750);
location = new PVector(100,50);
velocity = new PVector(0.0,2.1);
upwardForce = new PVector(0.0,-10.0);
gravity = new PVector(0,0.4);
bg = loadImage("bg.png");
bg.resize(1600,1600);
background(0);
for(int i =0; i< 20;i++){
xarray[i]= i*100;
yarray[i] = 750-int(random(10))*50;
}
}
int xd =0, yd=0;
void draw() {
background(0);
noStroke();
xd--;
yd++;
// display image twice:
image(bg, y, 0);
image(bg, y+bg.height, 0);
// pos
y--;
if (y<-bg.height)
y=0;
for (int i = 0;i< 20;i++){
if (xarray[i] <100 && xarray[i]+100 >100){
fill(255,0,0);
}
else {
fill(255);
}
rect(xarray[i],yarray[i],100,1200);
fill(255);
xarray[i]=xarray[i]-4;
//yarray[i]=yarray[i]+1;
if (xarray[i] + 100 < 0){
xarray[i]+=2000;
// yarray[i]-=850;
}
}
// changing Position
x=x+speed*directionX;
y=y+speed*directionY;
// check boundaries
if ((x>width-radius) || (x<radius))
{
directionX=-directionX;
}
if ((y>height-radius) || (y<radius))
{
directionY=-directionY;
}
// draw
// if(direction==1)
// Add velocity to the location.
location.add(velocity);
// Add gravity to velocity
velocity.add(gravity);
// Bounce off edges
if ((location.x > width) || (location.x < 0)) {
velocity.x = velocity.x * -1;
}
if ((location.y > height) || (location.y < 0)){
// We're reducing velocity ever so slightly
// when it hits the bottom of the window
velocity.y = velocity.y * -0.95;
location.y = height;
}
// Display circle at location vector
stroke(255);
strokeWeight(0);
fill(255);
ellipse(location.x,location.y,30,30);
}
void keyPressed()
{
velocity.add(upwardForce);
}
# 1 楼答案
以下是一些建议:
最好使用矩形类。这样,就不必将位置存储在数组中,collide函数可以是该类的一个方法。只调用矩形的位置“x”和“y”更容易,但这显然与您在代码顶部声明的x和y全局变量相冲突。假设你想让球在碰撞时反弹,你需要一个“ballLastx”和一个“ballLasty”来跟踪球来自哪个方向。您还需要将矩形存储在数组或arrayList中。应该是这样的:
至于矩形类,下面是它可能的样子:
然后,在设置函数中,可以在for循环中声明矩形类:
为了检测碰撞并弹起球,您需要在所有矩形中循环,查看球是否应从其中任何一个矩形中弹起:
最后,在移动当前位置之前,不要忘记将lastLocation PVector设置为当前位置:
希望这有帮助
# 2 楼答案
我们能给你的最好建议是break your problem down into smaller steps并一次一个地采取这些步骤
例如,你能创建一个简单的草图,只显示一个硬编码的圆和一个硬编码的矩形吗?现在添加一些代码,如果它们发生冲突,则将消息打印到控制台。你必须对collision detection进行一些研究,但这里有一个提示:一种常见的技术是将球视为矩形,这样你就可以进行矩形碰撞检测
让它自己完美地工作,然后一小步一小步地前进。你能在草图上再加一个矩形吗?再来一杯怎么样
然后,如果你陷入困境,你可以发布一个MCVE(不是你的整个项目,只是一个小例子)以及一个更具体的问题。祝你好运