Gradually accelerate sprite on key pressed; gradually decelerate on key released

后端 未结 4 1157
甜味超标
甜味超标 2020-12-21 11:16

I\'ve been trying to figure out how I can gradually accelerate a sprite on key pressed and then once the key is released, gradually slow down to a stop, muc

4条回答
  •  [愿得一人]
    2020-12-21 11:49

    There are two "concepts" from physics which you need to implement: Speed and friction.

    Here is a simple example in 2D. You may also use wrapper classes to combine the x/y variables into a single object and provide handy methods to alter their content.

    Each object needs to have a position and a speed variable. We also need friction, which is a constant for each material (as your object probably always travels in the same material, we will just model friction to be constant). In this simple simulation, friction gets weaker, as the value approaches 1. That means at friction=1 you have no friction and at friction=0 your objects will stop immediately:

    public class PhysicsObject{
        public static final double FRICTION = 0.99;
        private double posX;
        private double posY;
        private double speedX = 0;
        private double speedY = 0;
        public PhysicsObject(double posX, double posY){
            this.posX = posX;
            this.posY = posY;
        }
        public void accelerate(double accelerationX, double accelerationY){
            speedX += accelerationX;
            speedY += accelerationY;
        }
        public void update(){
            posX += speedX;
            posY += speedY;
            speedX *= FRICTION;
            speedY *= FRICTION;
        }
        public double getPosX(){
            return posX;
        }
        public double getPosY(){
            return posY;
        }
    }
    

    Notice that your object has an update method. this method needs to be called on all objects in your scene regularly, to apply the movement. In this method you could also process collision detection and enemies could do their AI logic..

提交回复
热议问题