1
\$\begingroup\$

I am developing an Asteroids type game in Java, using a custom Vector2D class for the Ship. I have a vector object for its position, direction and velocity. I am having an issue with the ship deceleration, currently when there is no thrust (forward key is released) then I multiply my velocity vector by the Drag constant which is 0.3. However the ships speed does not decelerate and will stop abruptly instead, upon releasing the thrust key.

Here is the update method in my Ship Class:

public void update() {
    velocity = new Vector2D(direction);

    if(ctrl.action().turn > 0) {
        direction.rotate(ctrl.action().turn / STEER_RATE);
    }
    else if(ctrl.action().turn < 0){
        direction.rotate(ctrl.action().turn / STEER_RATE);
    }

    //Acceleration
    if(ctrl.action().thrust == 1) {
        velocity.addScaled(direction, DT).mult(MAG_ACC);
    }
    //Deceleration
    else if(ctrl.action().thrust == 0){
        velocity.mult(DRAG);
    }
    position.addScaled(velocity, DT);
    position.wrap(FRAME_WIDTH, FRAME_HEIGHT);
}

Contructor:

public Ship (Controller ctrl) {
    centerX = FRAME_WIDTH/2.0;
    centerY = FRAME_HEIGHT/2.0;
    this.ctrl = ctrl;
    position = new Vector2D(centerX, centerY);
    direction = new Vector2D(position).normalise();
    velocity = new Vector2D(direction);
}

I'd like to ask how I can slow the ship velocity rather than it losing all of its speed instantly. If more code is required I am happy to show it.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Why are you recreating your velocity vector from scratch in every update (new Vector2D(direction))? This looks like it would block you from making any gradual changes to it that accumulate from one frame to the next. \$\endgroup\$
    – DMGregory
    Commented Mar 7, 2019 at 17:44

1 Answer 1

1
\$\begingroup\$

You're recreating the velocity vector every frame as DMGregory pointed out already.

The newly created vector likely has a value of 0 on all axis so multiplying it with 0.3 results in a velocity of 0.

The other case "ctrl.action().thrust == 1" only works because you are always adding a value first.

Just move the velocity-vector object out of the function and into the class scope. You will have to adjust your acceleration values and add upper and lower bounds for the velocity now though, since you're not recreating it every time.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .