傍墙反射

时间:2018-12-03 23:59:11

标签: java animation graphics game-development pong

我正在用Java制作乒乓球类游戏,我试图使球从墙壁上弹起,但是只要球撞到球,它只会停下来,不会从墙壁上反射出来,我似乎无法找出原因。

处理球运动的球类

public class Ball {
private double x;
private double y;
private double time;
private double  xreflection=1.0;
private double yreflection=1.0;
private BallTrajectory traj=new BallTrajectory(20, 20);

public Ball(double x, double y) {
    this.x=x;
    this.y=y;
}
public void tick() {
        time+=1.0/60.0;
        if(x==0)
            xreflection=1.0;
        else if(x==Game.Width-15)
            xreflection=-1.0;
        if(y==0)
            yreflection=1.0;
        else if(y==Game.Height-15)
            yreflection=-1.0;
    x+=traj.xvel()*xreflection;
    y-=traj.yvel(time)*yreflection;

}
public void render(Graphics g) {
    g.setColor(Color.pink);
    g.fillOval((int)x, (int)y, 15,15);
}

}

此类处理球以弹丸形式运动时的轨迹

public class BallTrajectory {
private double initvel;
private double theta;

public BallTrajectory(double initvel, double theta) {
    this.initvel=initvel;
    this.theta=theta;
}
public double xvel() {
    double xvelo=initvel*Math.cos(Math.toRadians(theta));
    return xvelo;
}

public double yvel(double time) {
    double yvelo=initvel*Math.sin(Math.toRadians(theta))-(9.8*time);
    return yvelo;
}

public double xpos(double time) {
    double xpos=initvel*Math.cos(Math.toRadians(theta))*time;
    return xpos;
}

public double ypos(double time) {
    double ypos=initvel*Math.sin(Math.toRadians(theta))*time-.5*9.8*Math.pow(time, 2);
    return ypos;
}

1 个答案:

答案 0 :(得分:2)

如果不进行大量测试,我建议x不可能完全等于Game.Width0。相反,您应该测试该值是否在“范围内”,例如...

public void tick() {
  time += 1.0 / 60.0;
  if (x <= 0) {
    xreflection = 1.0;
  } else if (x >= Game.Width - 15) {
    xreflection = -1.0;
  }
  if (y <= 0) {
    yreflection = 1.0;
  } else if (y >= Game.Height - 15) {
    yreflection = -1.0;
  }
  x += traj.xvel() * xreflection;
  y -= traj.yvel(time) * yreflection;
}

您还应该开始花时间学习如何调试代码,这是您需要做的很多事情,从检查桌面逻辑到使用打印语句和调试器