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

2014/8/16

Need Help With HealthBar by Sharing Variables

BobFisher3 BobFisher3

2014/8/16

#
I have been trying to create a health bar where when the player controlled character (MainCharacter) is hit by an enemy (Flame) a third class which contains a health bar image changes to accommodate for the damage. I am a bit stuck when it comes to 'sharing' the variables. I have a variable called "health" and when there is a collision between the enemy and the main character, it should become one less. This should then take effect in the Health bar class and its image be changed. Right now there are no syntax errors but it appears as though the health variable is not actually being affected. Here is my code for the Main Character:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;

/**
 * Write a description of class MainCharacter here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class MainCharacter extends Actor
{
    /**
     * Act - do whatever the MainCharacter wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        checkFall();
        walk();
        rebound();
    }
   private int speed = 4; // running speed (sideways)
   private int vSpeed = 0; //velocity speed
   private int acceleration = 2; 
   private int jumpStrength = 23;//jump height
   
   public void walk(){
    if (onGround() && Greenfoot.isKeyDown("w")){ //checks the character is on the ground
           jump();//runs jump
    }
        if (Greenfoot.isKeyDown("d")){//checks if the right key is being pressed
        moveRight();//walks the character to the right
    }
    if (Greenfoot.isKeyDown("a")){//checks if the a key is being pressed
        moveLeft();//walks the character to the left
        
    }
}
 public void jump()
    {
        vSpeed = -jumpStrength; //takes the jump strenght from the v speed (negative fall which makes jump)
        fall();//makes the character fall after it has jumped
    }
    public void checkFall()
    {
        if(onGround()) 
        {
            vSpeed = 0; //sets velocity to 0 (not falling) when the character is on the ground
        }
        else 
        {
            fall();
        }
    }
    public boolean onGround()
    {
        int myHeight = getImage().getHeight();    
        Actor under = getOneObjectAtOffset(0, myHeight/2, Board.class);
        return under != null;
    }
    public void fall()
    {
        setLocation ( getX(), getY() + vSpeed);
        vSpeed = vSpeed + acceleration; //adds acceleration to the vSpeed which is 0 (makes positive velocity which makes fall)
    } 
    public void moveRight()
    {
        setImage("ppl2Right.png");
        setLocation ( getX() + speed, getY() ); //adjusts movment based on speed set
        
    }  
    public void moveLeft()
    {
        setImage("ppl2.png");
        setLocation ( getX() - speed, getY() );//adjusts movment based on speed set
        
    }
    public void rebound()
    {
       Actor flame = getOneIntersectingObject(Flame.class);
       Health health = new Health();
        if(flame== null)
        {
            //do nothing because not intersecting    
        }
        else if(onGround())
        {
            bounce(); //runs the rebound
            health.setHealth(-1);
        }
        else
        {
          health.setHealth(-1); 
            
        }
    
}
    public void bounce()
    {
        setLocation ( getX() + 90, getY() -5);
        setLocation (getX() + 3, getY() );
    }
}
And for the enemy class:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Flame here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Flame extends Actor
{
    /**
     * Act - do whatever the Flame wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
       // moveAround();
      move();
   }  
   private int a = 1;
   private boolean swi = true;
    private void move(){
    moveRight();
    moveLeft();
   }
    private void moveRight(){
        if(swi == true){
         setLocation ( getX() + 1, getY() );
         Greenfoot.delay(1);
         a++;
         if(a>350){
             swi = false;
            }
     }
   }
    private void moveLeft(){
       if(swi == false){
         setLocation ( getX() - 1, getY() );
         Greenfoot.delay(1);
         a--;
         if(a<1){
             swi = true;
            }
     }
     }
}
And for the Health Bar Class:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Health here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Health extends Actor
{
    /**
     * Act - do whatever the Health wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        healthStatus();
    } 
    private int health = 4;
    public void setHealth(int points) {
        health = health + points; 
    }
    public int getHealth() {
        return health;
    }
    public void healthStatus()
    {
        switch (health)
        {
           case 1:
           setImage("health25.png");
           break;
           case 2:
           setImage("health50.png");
           break;
           case 3:
           setImage("health75.png"); 
           break;
           case 4:
           setImage("healthMax.png");
           break;
           default:break;
        }
    }
}
Thankyou so much for your help in advance :D
BobFisher3 BobFisher3

2014/8/16

#
One more thing, when the MainCaracter is falling at too great of a speed, it always falls through my ground object, is there a way to prevent this?
BobFisher3 BobFisher3

2014/8/16

#
Managed to create a fix for falling through the world if anyone is interested, in my fall() method I have added a parameter where if the vSpeed can not be greater than 22 and when it reaches 20 it is reset to 5.
BobFisher3 BobFisher3

2014/8/16

#
Idea's anyone?
danpost danpost

2014/8/16

#
Your 'rebound' method is creating a new Health object and changing its value. Then, that healthbar is flagged for garbage collection when the method is exited (no more references to that healthbar). You need to reference and change the Health object that is already in the world, not a new one.
Health health = (Health)getWorld().getObjects(Health.class).get(0);
would get that reference, provided you always have one in the world to reference. You can remove the 'act' method from the Health class and put a call to 'healthStatus' in the 'setHealth' method after adjusting the value of the 'health' field (you only need to adjust the image when the value changes).
BobFisher3 BobFisher3

2014/8/16

#
Ohhh that makes sense. I was a but unsure when I added the create new Health() but I didnt't know what else to do. This worked great :D. Thankyou so much :D
BobFisher3 BobFisher3

2014/8/16

#
Ok one more if you have time, I'm getting an Out of Bounds Exception when I run these lines of code: For My Star:
    public void addPower()
    {
        Actor maincharacter = getOneIntersectingObject(MainCharacter.class);
            if(maincharacter == null)
            {
                //do nothing because its not touching
            }
            else
            {
               StarPower starpower = (StarPower)getWorld().getObjects(StarPower.class).get(0); 
               starpower.setStar(+1);
               getWorld().removeObject(this);
            }
    }
And My StarPower Code:
public void act() 
    {
        changePower();
    } 
    private int starpwr = 0;
    public String starPower = "Star Power: "+ starpwr;
    public void draw()
    {
         GreenfootImage  ImageText = new GreenfootImage(starPower, 18, Color.BLACK,Color.BLACK); 
    } 
    
    public void setStar(int points) {  
        starpwr = starpwr + points;  
    }  
    public int getStarPower() {  
        return starpwr;  
    }  
    public void changePower(){
                       System.out.print(starpwr);
    }
danpost danpost

2014/8/16

#
I am not sure what your StarPower object is supposed to be. Please explain. On your error, line 10 of your 'addPower' method is the only place I could find that would return that type error. You are trying to get the first element from a list of 'StarPower' object in your world when the list, obviously, contains no elements.
BobFisher3 BobFisher3

2014/8/16

#
Okay, so I have these 'stars' on my map then when collected add to the characters 'star power'. How do I go about adding the object to the list?
BobFisher3 BobFisher3

2014/8/16

#
OHHHH, I should probably add it to the world before trying to add somethignt it :3
danpost danpost

2014/8/16

#
The only import statement you need in your MainCharacter class is
import greenfoot.*;
BobFisher3 BobFisher3

2014/8/16

#
Okay and how do I go about setting a string as an image for the StarPower class? I want to make it so when the power rises it displays it as a string. I tried with GreenfootImage ImageText = new GreenfootImage(starPower, 18, Color.BLACK,Color.BLACK); } doesn't seem to do it though :/
BobFisher3 BobFisher3

2014/8/17

#
No need, fixed it :D
You need to login to post a reply.