Java Pong游戏碰撞检测问题

时间:2016-08-22 01:06:18

标签: java eclipse

我对Java很新,可以使用一些帮助。我已经创建了Pong游戏(使用Eclipse),并且在大多数情况下,它的功能非常好。但是,碰撞检测有些不对劲。球从人控桨上反弹就好了,但总是直接通过AI控制的桨,我不能为我的生活弄清楚我的代码中有什么问题。这是代码:

主要班级"网球":

package PongV2;

import java.awt.Color;
import java.awt.Graphics;

public class AIPaddle implements Paddle{
double y, yVel;
boolean upAccel, downAccel;
final double GRAVITY = 0.94;
int player, x;
Ball b1;

public AIPaddle(int player, Ball b){
    upAccel = false; downAccel = false;
    b1 = b;
    y = 210; yVel = 0;
    if(player == 1)
        x = 20;
    else
        x = 660;
}

public void draw(Graphics g) {
    g.setColor(Color.white);
    g.fillRect(x, (int)y, 20, 80);

}

public void move() {
    y = b1.getY() -40;


     if(y < 0)
         y = 0;
     if(y > 420)
         y = 420;

}


public int getY() {
    return (int)y;
}

}

另外看看&#34; AIPaddle&#34;课程,如果有人需要看到它:

package PongV2;

import java.awt.Color;
import java.awt.Graphics;

public class Ball {
double xVel, yVel, x, y;

public Ball(){
    x = 350;
    y = 250;
    xVel = getRandomSpeed() * getRandomDirection();
    yVel = getRandomSpeed() * getRandomDirection();
}

public double getRandomSpeed(){
    return(Math.random() *3 + 2);
}

public int getRandomDirection(){
    int rand = (int)(Math.random() * 2);
    if(rand == 1)
        return 1;
    else
        return -1;
}

public void draw(Graphics g){
    g.setColor(Color.white); 
    g.fillOval((int)x-10, (int)y-10, 20, 20);
}

public void checkPaddleCollision(Paddle p1, Paddle p2){
    if (x <= 50){
       if(y >= p1.getY() && y <= p1.getY() + 80){
           xVel = -xVel;
}
    else if(x >= 650){
        if(y >= p2.getY() && y <= p2.getY() + 80)
            xVel = -xVel;
    }
    }
}

public void move(){
    x += xVel;
    y += yVel;

    if(y < 10)
        yVel = -yVel;
    if(y > 490)
        yVel = -yVel;
}

public int getX(){
    return (int)x;
}

public int getY(){
    return (int)y;
}

}

&#34;球&#34;类:

["1"]
["1","2"]
["1","2","3"]
["1","2","3","4"]

有人可以告知我的代码需要纠正的地方吗?感谢。

1 个答案:

答案 0 :(得分:1)

这是checkPaddleCollisionMethod中的if语句。你现在就拥有这个。

if(...) {
    if(...) {
    }
    else if(...) {
        if(...) {
        }
    }
}

else if与第二个if并行,而不是第一个。你想要一个更像这样的结构。

if(...) {
    if(...) {
    }
}
else if(...) {
    if(...) {
    }
}
相关问题