一种java方法,它逐个检查球的四条边,看球是否与墙相撞
在代码中添加一个方法,逐个检查球的四条边,检查该边是否与窗口的边发生碰撞。如果是这样,它应该相应地改变方向。例如,如果球向东北移动(↗) 而顶部边缘击中了屏幕顶部,它将改变方向为东南方向(↘) 这样球就会从边缘反弹。(请记住,如果球沿对角线方向直接进入一个角落,两条边可能同时击中,使其沿相反的对角线方向直接反弹。)
我不知道如何得到椭圆形的四边。我已经完成了其他4个方向(上、下、左、右),但不知道如何处理窗户的角落
public void move()
{
//direction right
if(dir == 1)
{
int x = ball.getX();
int y = ball.getY();
ball.setLocation(x + 1,y);
if(x>425)
{
dir = 2;
}
}
//direction left
if(dir == 2)
{
int x = ball.getX();
int y = ball.getY();
ball.setLocation(x - 1,y);
if(x<0)
{
dir = 1;
}
}
//direction down
if(dir == 3)
{
int x = ball.getX();
int y = ball.getY();
ball.setLocation(x,y + 1);
if(y>425)
{
dir = 4;
}
}
//direction up
if(dir == 4)
{
int x = ball.getX();
int y = ball.getY();
ball.setLocation(x ,y - 1);
if(y<0)
{
dir = 3;
}
}
//direction bottom right corner
if(dir == 5)
{
int x = ball.getX();
int y = ball.getY();
ball.setLocation(x + 1,y + 1);
}
//direction upper right corner
if(dir == 6)
{
int x = ball.getX();
int y = ball.getY();
ball.setLocation(x + 1,y - 1);
}
//direction bottom left corner
if(dir == 7)
{
int x = ball.getX();
int y = ball.getY();
ball.setLocation(x - 1,y + 1);
}
//direction upper left corner
if(dir == 8)
{
int x = ball.getX();
int y = ball.getY();
ball.setLocation(x - 1,y - 1);
}
}
最后,确保在移动球时调用此方法。这样,在将球沿其当前方向移动1个像素后,运行该方法检查球是否碰到任何边,并更改方向。在这一点上,你的球应该在屏幕上来回移动,同时弹跳
共 (0) 个答案