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

2017/4/6

Jump with Gravity

Fifilein Fifilein

2017/4/6

#
Hi! I am working on a Jump and Run game now.And I want my actor to jump and then fall down.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Spieler here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Spieler extends Actor
{
  int  acceleration = 2;
  int vSpeed = 0;
  int speed = 5;
  int jumpStrenght = 2;
  
    /**
     * Act - do whatever the Spieler wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        // Add your action code here.
        //if ( getObjects(GameOver.class).isEmpty() && ! getObjects(Grape.class).isEmpty())
         
         
    } 
    
    public boolean onGround()
    {
     Actor under = getOneObjectAtOffset(0, getImage().getHeight()/2 + 2, Ground.class);
       return under != null;
    }
    public void Fall()
    {
     setLocation (getX(), getY() + vSpeed);
     vSpeed = vSpeed += acceleration;
    }
    public void checkFall()
    {
     if (onGround())
     {
        vSpeed = 0;}
      else {
        Fall();
     }
    }
    public void checkKeys()
    {
       if (Greenfoot.isKeyDown("left"))
       {
         moveLeft();
        }
       if(Greenfoot.isKeyDown("right"))
       {
          moveRight(); 
        }
        if(Greenfoot.isKeyDown("space"))
       {
          jump(); 
        }
   }
   public void jump()
   {
       vSpeed = -jumpStrenght;
       Fall();
       
    }
  public void moveLeft()
  {
      setLocation(getX() - speed, getY());  
   }
  public void moveRight()
{
  setLocation(getX() + speed, getY());  
}
}
I tied this for jump but it does not work like it should. With this Code I fly when I am pressing space, but it is not like a want, I want it to jump. Can you help me? Thanks, Fifilein
Nosson1459 Nosson1459

2017/4/6

#
If you want your Spieler to jump then you'll have to:
  • Increase the jumpStrenght (jumpStrength) (and then if your scenario execution speed is on at least 50 then you should probably also decrease the acceleration)
  • Call the checkKeys() and checkFall() methods in the act() method.
  • Change the
    if (Greenfoot.isKeyDown("space"))
    on line 57 to
    if (Greenfoot.isKeyDown("space") && onGround())
Fifilein Fifilein

2017/4/7

#
Thank you now it works like it should
You need to login to post a reply.