Basically when i update the ball in my flipper (an Oval created with Graphics2D) it teleports to his next location, which is what I want it to do, but I would much rather have a smooth animation (And I also fear the crispy movement is gonna be hard to deal with for collisions).
So is there a way to get smoother movement?
The main class:
import Flipper.Ball;
import Flipper.Cabinet;
public class Main {
public static Cabinet cabinet;
public static Ball ball;
public static void main(String[] args) throws InterruptedException {
new Frame();
cabinet = new Cabinet();
ball = new Ball();
while (true)
update();
}
private static void update() throws InterruptedException {
ball.calcSpeed();
ball.move();
}
}
Frame class:
import javax.swing.*;
public class Frame extends JFrame {
Frame() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(new Panel());
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
Panel class (I left out all of the useless KeyListener/MouseListener methods that i haven't used yet):
mport javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Panel extends JPanel implements KeyListener, MouseListener {
Panel() {
this.setPreferredSize(new Dimension(Constant.WIDTH, Constant.HEIGHT));
this.setFocusable(true);
this.addMouseListener(this);
this.addKeyListener(this);
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
g2.draw(Main.cabinet.getShape());
g2.setColor(Color.BLUE);
g2.fillOval(Main.ball.getX(), Main.ball.getY(), Constant.BALLSIZE, Constant.BALLSIZE);
repaint();
}
}
Flipper classes:
package Flipper;
import main.Constant;
import java.awt.*;
public class Cabinet {
private Rectangle shape;
public Cabinet() {
this.shape = new Rectangle(Constant.WIDTH, Constant.HEIGHT);
}
public Rectangle getShape() {
return shape;
}
}
package Flipper;
import main.Constant;
import java.util.concurrent.TimeUnit;
public class Ball {
private int x;
private int y;
private int xSpeed = 1;
private int ySpeed = 10;
public Ball() {
this.x = 230;
this.y = 160;
}
public void calcSpeed() {
if (y >= Constant.HEIGHT - Constant.BALLSIZE)
ySpeed = ySpeed * -1;
if (y <= 0)
ySpeed = ySpeed * -1;
}
public void move() throws InterruptedException {
y += ySpeed;
TimeUnit.MILLISECONDS.sleep(50);
}
// Getters
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getxSpeed() {
return xSpeed;
}
public int getySpeed() {
return ySpeed;
}
// Setters
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setxSpeed(int xSpeed) {
this.xSpeed = xSpeed;
}
public void setySpeed(int ySpeed) {
this.ySpeed = ySpeed;
}
}