Java pong game graphics or geom 2D

My first project was to create a game pong. Com in Java

Here I calculate the angle of the ball after hitting the ball

int c = (int) Math.atan2(ball.getPosY(),ball.getPosX());
int delta_x = (int) (1 * Math.cos(c));

    int delta_y = (int) (1 * Math.sin(c));
    this.dx += delta_x;
    this.dy += delta_y;

With DX and Dy, I changed the X and Y positions of table tennis I draw my table tennis here

g.setColor(Color.WHITE);
g.fillOval(this.posX,this.posY,25,25);

If I want DX and Dy to be more accurate, I have to delta_ Y and Delta_ Change the type of X to double But fillOval () does not apply to two variables So I have to be in geom Point2D. Make my graphics in double?

Solution

Use the double value for Delta, but convert the final coordinates to int

Something like this (in pseudo code style):

int delta_x=1.3,delta_y=-0.4
public void update(){
   double x=(pong_ball.getX()+delta_x);
   double y=(pong_ball.getY()+delta_y);
   pong_ball.setX(x);
   pong_ball.setY(y);
}
// in the pong_ball code
public void paint(Graphics g){
   paintBall((int) x,(int) y);
}

Editor: sorry, I realized a mistake If the triangle is small enough, the ball won't move! Therefore, you need to store the coordinates of the ball in doubles and only cast it when you draw the ball at the end... Sorry

Edit 2: Please note that the above code is not compiled You need more code (such as actual X-Y fields, JFrame code, etc.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>