Code for a penguin that jumps -- Greenfoot programming
Find other posts in the same category: | |

Contents

To make a character that jumps when press the space key, watch this Greenfoot video tutorial

http://www.greenfoot.org/videos/jumping.mov

http://www.greenfoot.org/doc/videos.html

This is the code for the penguin in the tutorial

import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
* A small demo of a jumping movement.
*
* @author M K�lling
* @version 1.0
*/
public class Pengu extends Actor
{
private int speed = 7; // running speed (sideways)
private int vSpeed = 0;
private int acceleration = 2;
private int jumpStrength = 12;

/**
* Check keyboard input and act accordingly
*/
public void act()
{
checkKeys();
checkFall();
}


private void checkKeys()
{
if (Greenfoot.isKeyDown("left") )
{
setImage("pengu-left.png");
moveLeft();
}
if (Greenfoot.isKeyDown("right") )
{
setImage("pengu-right.png");
moveRight();
}
if (Greenfoot.isKeyDown("space") )
{
jump();
}
}


public void jump()
{
vSpeed = -jumpStrength;
fall();
}

public void checkFall()
{
if(onGround()) {
vSpeed = 0;
}
else {
fall();
}
}

public boolean onGround()
{
Actor under = getOneObjectAtOffset ( 0, getHeight() / 2, Ground.class);
return under != null;
}


public void fall()
{
setLocation ( getX(), getY() + vSpeed);
vSpeed = vSpeed + acceleration;
}

public void moveRight()
{
setLocation ( getX() + speed, getY() );
}


public void moveLeft()
{
setLocation ( getX() - speed, getY() );
}

}


Next Book Page

To see posts on the same topic, click the links below the name of the author at the top of this page.