I’m somewhat new to creating games in Java, however my current setup is such that the FPS on the paint method is bounded only by the system. So, my FPS tends to be between 300 and 450. In order to standardize movement speeds on objects, I’ve been dividing the increment by the FPS so that it will increment that total amount in a one second time-frame.
I have the following code. What I want to do it make it so that map.addEntity() is not called 300 or 400 times per second, in accordance with the FPS; but rather make it so that I can choose, for example, to make the projectile fire at 10 RPS or so. How can I achieve this?
public void mousePressed(MouseEvent e) {
if (gameStarted)
shootProjectile = true;
}
public void paint(Graphics g) {
if (shootProjectile)
map.addEntity(new Projectile("projectile.png", x, y, 0, projectileSpeed));
}
Don’t do that! Use a
Timeror aswingTimerto update everything at a constant rate. For example you could do something like this:Note that if you use a swing
Timer, your projectile updating will happen on the swing thread. If the updating hangs, your GUI will also hang.You also should not call
map.addEntityinsidepaint()sincepaint()does one thing and one thing only: paint everything. You can get around this but mixing up the code that updates things like position with code that renders the objects will eventually bite you.