This site requires JavaScript, please enable it in your browser!
Greenfoot back
ebollinger@sonorahigh.net
ebollinger@sonorahigh.net wrote ...

2018/9/19

need to learn gravity

hey i am a beginner and im trying to learn how to put gravity on my dragon so that he can walk on plateforms
can anyone help me?
danpost danpost

2018/9/20

#
ebollinger@sonorahigh.net wrote...
hey i am a beginner and im trying to learn how to put gravity on my dragon so that he can walk on plateforms
Gravity is a constant downward force. Use an instance field (a non-static variable declared within the class of the dragon but outside any code blocks) to track the vertical speed of the actor. In the act method of the class, increment it and set the location of the actor so that it moves vertically by the new value of the field:
private int ySpeed;

public void act()
{
    ySpeed++;
    setLocation(getX(), getY()+ySpeed);
After the vertical movement, you would check for a platforrm and, if encountered, adjust the vertical position so that the actor and the platforrm are one above the other (which way can be determined by the sign of the value of the 'ySpeed' field); afterwhich, the 'ySpeed' field should be zeroed (killing any accumulated vertical speed). Act method code might continue as follows:
Actor platforrm = getOneIntersectingObject(Platform.class);
if (platform != null)
{
    int dir = (int)Math.signum(ySpeed); // to determine vertical direction (landing on "feet" or head-hit)
    int myHeight = getImage().getHeight);
    int platformHeight = platform.getImage().getHeight();
    setLocation(getX(), platform.getY()-dir*(myHeight+platformHeight)/2);
    ySpeed = 0;
}
thanks
You need to login to post a reply.