This site requires JavaScript, please enable it in your browser!
Greenfoot back
Astralman
Astralman wrote ...

2016/11/19

How to apply gravity the simpliest way?

1
2
Astralman Astralman

2016/11/27

#
Which class?
Super_Hippo Super_Hippo

2016/11/27

#
The class which should be affected by the gravity.
Astralman Astralman

2016/11/27

#
That's all of it.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;

public class Ship extends SmoothMover
{
    private GreenfootImage Rocket;
    // private double mass;
    private static final double GRAVITY = 0.5;
    private int vSpeed;
 
    public Ship ()
    {
        Vector intial = new Vector(Greenfoot.getRandomNumber(360), .6);
        setRotation(270);
    }

    public void act() 
    {
        move();
        checkKeys();
        //applyForces();

        vSpeed += GRAVITY; // add constant acceleration due to gravity
        setLocation(getX(), getY()+vSpeed); // fall (or rise)
        // if collision, adjust location and zero vSpeed
    }

    public void checkKeys()
    {        
        if(Greenfoot.isKeyDown("left")) {
            turn(-5);
        }        
        if(Greenfoot.isKeyDown("right")) {
            turn(5);
        }

        ignite (Greenfoot.isKeyDown("down"));

    }

    private void ignite (boolean thrust)

    {
        if (thrust == true)
        {
            Vector power = new Vector(getRotation(), .2);
            addToVelocity(power);
            setImage("rocketWithThrust.png");
        }
        else
        {
            setImage("rocket.png");
        }
    }
}
danpost danpost

2016/11/27

#
You cannot expect to add a double value to an int value and retain the precision of the double. 'vSpeed' needs to be maintained as a double type value.
Astralman Astralman

2016/11/27

#
Thanks, it works.
 private static final double GRAVITY = 0.5;
 private double vSpeed;
You need to login to post a reply.
1
2