I am making a game where you have to jump onto platforms. You can also move forward in the air in the game.
import greenfoot.*;
/**
* Write a description of class ball here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class ball extends Actor
{
/**
* Act - do whatever the Skelaton wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
private int gravity = 0;
public void act()
{
if (onGround() && Greenfoot.isKeyDown("up"))
{
System.out.println("Actor should jump");
System.out.println("Actor at: (" + getX() + ", " + getY() + ")");
jump(); // Add your action code here.
}
if (Greenfoot.isKeyDown("right"))
{
move (3);
}
if (Greenfoot.isKeyDown("left"))
{
move (-3);
}
checkFall();//fill this in with what you want,
//but add this here:
if (onGround() && Greenfoot.isKeyDown("up"))
{
jump();
checkFall();
}
}
private void checkFall()
{
if(!onGround() || gravity < 0)
fall();
}
private boolean onGround()
{
int myHeight = getImage().getHeight();
Actor ground = getOneObjectAtOffset(0, myHeight/2, Ground.class);
if(ground != null)//if the ground is really there...
return true;
//(if not, return false)
return false;
}
//this is quite like SPower's method
private void fall()
{
setLocation(getX(), getY() + gravity);
gravity++;//the player will accelerate as he falls
}
private void jump()
{
gravity -= 20;//or choose 10 or 15 or whatever works
}
}