0
\$\begingroup\$

I am writing a little experimental 2D program in Java to understand the basics of physics in games. I read this article on game physics to get me started and want to implement the simple Euler method (it is discouraged in the article, but this is just an experiment). My "Ball" class looks like this:

public class Ball {
    double x, xv, fx; //position, velocity, force
    int xdir = -1;
    double rad = 20;
    double mass = 1;

    public void tick(){
        x = x + (xv*xdir) * STEPTIME;
        xv = xv + (fx/mass) * STEPTIME;
        fx = 0;
    }
//STEPTIME is 0.02

For now, I want to focus on horizontal movement. In the end, I want to be able to drag the mouse in the window and have a bawn spall with force applied to it depending on the distance of the drag. The tick() function implements the following equations (from the article):

  • acceleration = force divided by mass
  • change in velocity = acceleration * delta time
  • change in position = velocity * delta time

My problem is, that I do not know how to decrease the velocity again. When force is applied in a single frame, velocity will then ben constant. If force is applied continuously, velocity will become infinite. Since the ball is supposed to return to an idle state after it force has been applied to it in a single frame, the velocity has to decay over time. If I apply a constant negative velocity (to simulate drag), then velocity will soon be negative and the ball will move in the opposite direction.

What is a good way / best practice to decay the velocity of an object over time ?

\$\endgroup\$
  • 1
    \$\begingroup\$ Add friction or drag. This value is calculated based on the current velocity. So when the current velocity is zero, the drag or friction are zero. \$\endgroup\$ – MichaelHouse May 31 '13 at 17:50
  • \$\begingroup\$ Heh, a programmer's way of discovering one of Newton's laws - an object in motion tends to stay in motion unless acted upon by an outside force (in this case it would be friction) \$\endgroup\$ – Katana314 May 31 '13 at 20:32
  • \$\begingroup\$ Just a quick note: by simply swapping the position and velocity update lines, the integration become "symplectic Euler" and, while still as inaccurate, it has better conservation of energy because you are using v(t+1) rather than v(t) in the position update. \$\endgroup\$ – DaleyPaley May 31 '13 at 22:29

Browse other questions tagged or ask your own question.