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

2021/3/22

Put 2 Codes from 2 Classes into 1 Class

PetrusderEchte PetrusderEchte

2021/3/22

#
Hey! I need your help! I have 2 Codes:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Jumper here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Jumper1 extends Actor
{
    private final int GRAVITY = 1; 
    private int velocity; 
    public Jumper1() { 
        velocity = 5; 
    }    
    public void act() 
    {
        fall(); 
        if (Greenfoot.isKeyDown("space") && getY() > getWorld().getHeight() -50) jump();
    }    
    public void fall() { 
        setLocation(getX(), getY() + velocity); 
        if (getY() > getWorld().getHeight() -50) velocity = 5; 
        else velocity += GRAVITY;
    }
    public void jump() {
        
        velocity = -20;  
    }
}



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

/**
 * Write a description of class Mann here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Mann extends Actor
{
    /**
     * Act - do whatever the Mann wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        // Add yo public void act() 
    { 
       int speed = 1;
      
      
      
     
       if (Greenfoot.isKeyDown("a"))
       setLocation(getX() - speed, getY());
       if (Greenfoot.isKeyDown("d"))
       setLocation(getX() + speed, getY());
       
      
    }    
} 
}
the first code is for jumping and the second is that you can move. But how can i get these both codes into 1? So that in the end i have one figure that can move and jump. Thanks a lot and best greetings
Risen Risen

2021/3/22

#
Something like this?
import greenfoot.*;  
public class Jumper1 extends Actor
{
    private final int GRAVITY = 1; 
    private int velocity; 
int speed = 1;
    public Jumper1() { 
        velocity = 5; 
    }    
    public void act() 
    {
mover();
        fall(); 
        if (Greenfoot.isKeyDown("space") && getY() > getWorld().getHeight() -50) jump();
    }    
    public void fall() { 
        setLocation(getX(), getY() + velocity); 
        if (getY() > getWorld().getHeight() -50) velocity = 5; 
        else velocity += GRAVITY;
    }
    public void jump() {
         
        velocity = -20;  
    }
public void mover() {
       if (Greenfoot.isKeyDown("a"))
       setLocation(getX() - speed, getY());
       if (Greenfoot.isKeyDown("d"))
       setLocation(getX() + speed, getY());
}
}
        
danpost danpost

2021/3/22

#
OR: In Mann class, you can change line 9 to:
public class Mann extends Jumper1
and add as first line in act:
super.act();
You need to login to post a reply.