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

2015/12/14

Why doesn't this boolean work?

SonofArith SonofArith

2015/12/14

#
I am trying to make my character throw knives as a weapon. At the beginning of the game, I want it to be where you pick up the knife, while it is stationary, and once you pick it up then you can throw them. I thought this would work. First, I have a boolean, hasKnife, that is false; Second, I make a method that removes the knife when you touch it, and sets the boolean to true:
public void pickUpKnife()
    {       
        Actor tKnife;
        tKnife = getOneObjectAtOffset(0, 0, ThrowingKnife.class);
        if(tKnife != null)
        {
            World world = getWorld();
            getWorld().removeObject(tKnife);
        }
        hasKnife = true;
    }
After that I have the method to actually throw the knives:
public void throwKnife()
    {
        if(Greenfoot.isKeyDown("space"))
        {
            getWorld().addObject(new ThrowingKnife(), getX(), getY());
        }
    }
To make sure that you couldn't do throwKnife() without picking up the knife first, I did this in the act method:
public void act() 
    {
        hitEnemy();
        movement();
        collision();

        if(hasKnife = false)
        {
            pickUpKnife();   
        }        

        if(hasKnife = true)
        {
            throwKnife();
        }

    }
So why doesn't it work? The stationary knife doesn't disappear, and it spawns knife when ever you press space.
danpost danpost

2015/12/14

#
You are not controlling the value of 'hasKnife' properly. You should set it to 'true' inside the 'if (tKnife != null)' block -- not after the block which always sets it to true regardless; and you need to reset the value to 'false' when throwing the knife. You also need to make sure that you do not spawn the knife being thrown at a location where 'getOneObjectAtOffset(0, 0, ThrowingKnife.class)' will pick it right back up again.
danpost danpost

2015/12/14

#
Another thing is that you need to compare the value of 'hasKnife' to 'true' or 'false', not assign 'true' and 'false' to the field as you are within the 'if' conditional expression. Use '==' for comparing; '=' is for assignment operations.
You need to login to post a reply.