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

2020/3/17

Jumping Physics

SnowFlurry SnowFlurry

2020/3/17

#
I'm new to Greenfoot, and I am trying to make a simple platformer to start off. I am having trouble with getting my jumping code working when I press the up arrow key. Here is part of my code:
    private int grav = -2;
        private int x_vel=0;
        private int y_vel=0;

    public void act() 
    {        
        if(Greenfoot.isKeyDown("right")){
            move(2);
        }
        if(Greenfoot.isKeyDown("left")){
            move(-2);
        }
        if(Greenfoot.isKeyDown("up")){
            y_vel=6;
            int ground=getY();
            do{
            setLocation(getX(),getY()-y_vel);
            y_vel+=grav;
            }while(ground!=getY());
            
            //another method I attempted while trying to figure out 
            //what exactly is causing the problm
            /*setLocation(getX(),getY()-6);
            setLocation(getX(),getY()-4);
            setLocation(getX(),getY()-2);
            setLocation(getX(),getY());
            setLocation(getX(),getY()+2);
            setLocation(getX(),getY()+4);
            setLocation(getX(),getY()+6);*/
        }
    } 
I am setting a value for acceleration caused by gravity and a initial velocity, then looping the process of increasing the y-value by the acceleration until the y-coordinate hits the ground again. But this does not move the object at all when I press the up arrow key. I feel like I'm not understanding how Greenfoot works, please let me know what I'm doing wrong. Thanks in advance!
danpost danpost

2020/3/17

#
SnowFlurry wrote...
I feel like I'm not understanding how Greenfoot works
It is coding, in general, that you have a particular misunderstanding of. A loop (for, do or while) will execute completely within a single act (or between frames). The jump needs to be programmed as incremental steps. Refer to my Jump and Run Demo w/Moving Platform scenario for sample code (review the Who class).
SnowFlurry SnowFlurry

2020/3/24

#
Oh I see, thank you! The demo was very helpful.
You need to login to post a reply.