如何弹动移动球的球
问题描述:
好的,我在尝试在BlueJ上编程的游戏遇到了一些困难。到目前为止,我有一个弹跳的球,还有一个可以用鼠标移动的桨。我试图让球从我的球杆反弹,基本上我移动它的地方。如何弹动移动球的球
我有三个班,我知道它很长,但我真的可以使用一些帮助。
public class MAIN {
public void begin(){
Paddle = new Paddle(140,400,100,canvas);
ball = new Ball (180,50,canvas, Paddle)//ball can recognize paddle
}
public void onMousemove (Location p){
Paddle.move(p);
}
}
public class Paddle {
public Paddle (int x, int y, int s, DrawingCanvas c){
((JDrawingCanvas)c).setBackground(Color.green);
paddle = new FilledRect(x,y,s,10,c);
}
public void move (Location p){
paddle.moveTo(p.getX(),p.getY());
} //paddle, and to move paddle
}
public class Ball {
Drawing Canvas myCanvas;
FilledRect paddle;
FilledOval ball;
int dx = 3, dy = 5;
public Ball (int x, int y, int s, DrawingCanvas c, Paddle paddle){
myCanvas = c
((JDrawingCanvas)c).setBackground(Color.green);
ball = new FilledOval (x,y,s,s,c);
pad = paddle;
start();
}
public void run() //bounces the ball around
{
while(true){
if(ball.getX() <0 ||ball.getX() > myCanvas.getWidth()){
dx = dx;
}
if(ball.getY() <0 ||ball.getY() > myCanvas.getWidth()){
dy = dy;
}
move5();
pause(20);
}
public Rectangle getRectangle(){
return new Rectangle ((int)paddle.getX(), paddle.getY(),
paddle.getWidth(), paddle.getHeight();
}
public boolean collision (Ball p){
return getRectangle().intersects(p.getRectangle());
}
public void move5(){
ball.move(dx,dy)
}
public void collide(){
dx= -dx
dy=-dy
}
}
答
不要使用击中格为你的球时,检查每个帧,如果它与overlaping到upperor你的桨的下边界。如果是,则反转球的速度。 Sameb对x轴。
如果球的坐标(让y轴说)减去其半径小于线的y坐标并且球的y坐标加上其半径大于limne的y坐标并且球的x坐标+ - 其半径比线的终点的x坐标更小/更大。所以基本上你要检查球是在线的两端之间,而不是离线比自己的半径更远。如果这是球碰撞你的桨的边界的情况。
您应该可以使用与屏幕两侧相同的碰撞检测来检测球是否正在碰触桨。 –