So i made this code by following a video but it didn't get the results i wanted. I am very new to programming and i don't know what i am doing. This is for a school project :(
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Protagonist here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Protagonist extends Actor
{
private final int GRAVITY = 1;
private final int STEP=3;
private int velocity;
public Protagonist(){
velocity = 0;
}
/**
* Act - do whatever the Protagonist wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
fall();
if (Greenfoot.isKeyDown("space") && isOnSolidGround())jump();
move();
}
public void fall(){
setLocation (getX(),getY() + velocity);
if (isOnSolidGround()){
velocity=0;
while (isOnSolidGround()){
setLocation(getX(), getY()-1);
}
setLocation(getX(),getY() + 1);
}
else if(velocity < 0 && didBumpHead()){
velocity=0;
while(didBumpHead()){
setLocation(getX(), getY()+1);
}
}
else velocity+=GRAVITY;
}
public void jump(){
velocity=-8;
}
public void move(){
int x =getX();
int y=getY();
if (Greenfoot.isKeyDown("left")&& canMoveLeft()) x-=STEP;
if (Greenfoot.isKeyDown("right")&& canMoveRight()) x+=STEP;
setLocation(x,y);
}
public boolean isOnSolidGround(){
boolean isOnGround= false;
if(getY() > getWorld().getHeight()-50) isOnGround=true;
int imageWidth = getImage().getWidth();
int imageHeight= getImage().getHeight();
if(getOneObjectAtOffset(imageWidth/-1, imageHeight/1, Platform.class)!=null||
getOneObjectAtOffset(imageWidth/1, imageHeight/1, Platform.class)!=null)
isOnGround = true;
return isOnGround;
}
public boolean didBumpHead(){
boolean bumpedHead=false;
int imageWidth = getImage().getWidth();
int imageHeight= getImage().getHeight();
if(getOneObjectAtOffset(imageWidth/-1, imageHeight/-1, Platform.class)!=null||
getOneObjectAtOffset(imageWidth/1, imageHeight/-1, Platform.class)!=null)
bumpedHead= true;
return bumpedHead;
}
public boolean canMoveLeft(){
boolean canMoveLeft=true;
int imageWidth = getImage().getWidth();
int imageHeight= getImage().getHeight();
if(getOneObjectAtOffset(imageWidth/-1-STEP, imageHeight/-1, Platform.class)!=null||
getOneObjectAtOffset(imageWidth/-1-STEP, imageHeight/1-0, Platform.class)!=null)
canMoveLeft= false;
return canMoveLeft;
}
public boolean canMoveRight(){
boolean canMoveLeft=true;
int imageWidth = getImage().getWidth();
int imageHeight= getImage().getHeight();
if(getOneObjectAtOffset(imageWidth/1+STEP, imageHeight/-1, Platform.class)!=null||
getOneObjectAtOffset(imageWidth/1+STEP, imageHeight/1-0, Platform.class)!=null)
canMoveLeft= false;
return canMoveLeft;
}
}
