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

2015/3/19

Take hp

0gener 0gener

2015/3/19

#
Hello, I have a bullet class and a player class, what I want is when the bullet hits the player, the same loses health but I get this error: "non-static method hit(int) cannot be referenced from a static context". Here is what I got on player:
public class Player extends Human
{
        private int hp = 100;

        public void hit(int damage)
    {
        hp = hp - damage;
        if(hp <= 0)
        {
            Greenfoot.stop();
        }
    }
and the bullet:
public void hitPlayer()
    {
        Actor hit;
        hit = getOneObjectAtOffset(0, 0, Player.class);
        if(hit != null)
        {
            getWorld().removeObject(this);
            Player.hit(DMGE);
        }
    }
danpost danpost

2015/3/19

#
On line 8, you are asking the class, called Player, to take damage. The class is not what takes damage -- the object created from the class, or instance of the class, is what has 'health' and can be 'hit' to take damage. To avoid confusion, I will re-write your 'hitPlayer' method:
public void hitPlayer()
{
    Actor actor;
    actor = getOneObjectAtOffset(0, 0, Player.class);
    if(actor != null)
    {
        getWorld().removeObject(this);
        Player.hit(DMGE);
    }
}
All I did was change the name of the Actor variable 'hit' to 'actor' (because you are calling a 'hit' method at the end). Now, this 'actor' variable (previously called 'hit') holds an Actor object (or 'null') which is returned by the call to 'getOneObjectAtOffset'. If line 5 finds that the variable is not 'null', then you want to call the 'hit' method on that actor. However, the 'hit' method you want to call is not in the Actor class; but, instead, it is in your Player class. Therefore, we need to cast the actor as a Player type object:
Player player = (Player)actor;
Then, you can call the 'hit' method on the 'player' instance:
player.hit(DMGE);
The final steps can be combined, calling the 'hit' method on 'actor' cast as a Player type:
((Player)actor).hit(DMGE);
0gener 0gener

2015/3/19

#
Thank you very much for the explanation and for the code, it´s now working.
You need to login to post a reply.