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

2022/12/23

Adding gravity to my program

linvs1 linvs1

2022/12/23

#
Hi, i managed to let my character jump to a certain hight. But now i want him to get back down... how can i add some kind of Gravity? I already tried to use setLocation when the Player is not grounded (touching the object ground), but after adding that function he wouldn't jump at all : Method Grouded:
public boolean grounded()
    {
        if(isTouching(Boden.class)) 
        {
            return true;
        }
        else
        {
            return false; 
        }
    }
Method jump:
if(Greenfoot.isKeyDown("space"))
            {
                if(grounded()) 
                {
                    setImage("images/jumpking_sprungloading.png");
                    a = System.currentTimeMillis();
                    while(Greenfoot.isKeyDown("space"))
                    {
                        setImage("images/jumpking_sprungloading.png");
                    }
                    b = System.currentTimeMillis();
                    sprung = (int) b - (int) a; 
                    
                    if(sprung > maxSprung)
                    {
                        sprung = maxSprung;
                    }
                    setLocation(getX(), getY() - sprung / 4);
                }
            }
            else
            {
                setImage("images/jumpking_standard.png");
            }
(if you press longer you jump higher)
danpost danpost

2022/12/24

#
linvs1 wrote...
i managed to let my character jump to a certain hight. But now i want him to get back down... how can i add some kind of Gravity? I already tried to use setLocation when the Player is not grounded (touching the object ground), but after adding that function he wouldn't jump at all : Method Grouded: << Code Omitted >> Method jump: << Code Omitted >> (if you press longer you jump higher)
Thoughts on given code are: (1) using real time to control jump speed is not recommended; (2) using a while loop in the jump code will pause all actors not controlled from within that loop until the condition for the loop fails; (3) using setImage(String) multiple times per act and every act is not good programming, due to the fact that the file must be read from a file directory each time this method is called; You may want to look at my Jump and Run Demo w/Moving Platform scenario to view its codes for such a function.
linvs1 linvs1

2022/12/24

#
Thanks for your reply!! I am using Greenfoot in school and my teacher said i should do it like this...
You need to login to post a reply.