简体   繁体   中英

How can I add velocity to a movable object in Java?

Using this code as an example, how would I add a velocity component to an object?

class CircleFrame extends JPanel {
    static int x = 20;
    static int y = 20;
    int radius = 20;

    CircleFrame() {
        setSize(400,400);
    }

    @Override
    protected void paintComponent(Graphics g) {
        repaint();
        g.drawOval(x,y,radius,radius);
    }
}

This code allows the user to take control of a small circle in a JFrame using the left, right, up and down arrow keys. How can I add in velocity? For instance, while they are moving it to the right, the xvelocity becomes larger. Once they stop moving it, the velocity slowly decreases until the object has stopped. I was thinking threads are the answer here but I still don't understand them much.

Each move is a unique key press? Ie if i hold the key down, i only get one move? If that's the case and you just want to roughly calculate velocity, then you can call System.currentTimeMillis() on each of your press event handlers, keep it in a variable somewhere, and call it again on the next, then just compute the total displacement divided by the difference in time... if this is what you're trying to do comment and i'll write some code.

Another (more likely) possibility is you want the velocity to increase while they hold the key down... in that case, figure out the acceleration you want to impose.. use a second thread to increase the velocity and notify that action to decelerate to a stop when the keyUp event occurs.

int accel = 1;
boolean accelerating = false;
public void keyPressed(KeyEvent e)
{
   ...
   accelerating = true;
   new Thread() //anonymous inner class 
   { 
     public void run()
     {
       while (accelerating) { x += vel; vel += 1; }
       //no longer accelerating
       x = 0; //or decelerate gracefully with a similar loop as accel.
     }
  }.run();
}
public void keyUp(KeyEvent e) //or however you get a key release event
{
   accelerating = false;
}

modify this a bit to adapt it to your up/down/left/right, and figure out the acceleration that makes sense for you. you might even consider only accelerating up to a limit, and not any past a certain velocity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM