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

2013/1/28

Crosshairs Shooting

wafflepudding wafflepudding

2013/1/28

#
So I have code that makes Crosshairs (an actor) follow my mouse. When I click it, it's supposed to set the variable 'shoot' to true. The variable shoot is defined in the Actor Methods, which contains Crosshairs and Guy. When shoot is true, Guy is supposed to create a bullet at his location. Here's all the code involving shooting, why doesn't it work?
    public void shoot() //in Guy, defined in act.
    {
        if(shoot == true)
        {
            getWorld().addObject(new Bullet(), getX(), getY());
            shoot = false;
        }    
    }    
        public void setShoot() //in Crosshairs, defined in act.
    {
        if(Greenfoot.mouseClicked(this))
        {
            shoot = true;
        }   
    }    
public class Methods extends Actor //Methods contains Crosshairs and Guy.
{
    public boolean shoot;
That's about it. Nothing happens when I click on the Crosshairs.
danpost danpost

2013/1/28

#
The problem is this: When you create a Guy object, it acquires a 'shoot' field, and when you create a Crosshairs object it acquires a different 'shoot' field. So, changing the field in one and performing the check on the other (that has not been changed) will not find any change in its value. Therefore, no bullet will be created. If you want the classes to be able to share a common field among them, then make the field a 'static' field (which makes it a class field as opposed to an instance object field -- meaning you will have one field belonging to the class and not multiple field, one belonging to the each object created from that class). In the Methods class, define 'shoot' with:
public static boolean shoot;
davmac davmac

2013/1/28

#
Your post is confusing. Are Guy and Crosshairs seperate classes? I think this must be the case. When you say Methods "contains" Crosshairs and Guy, do you mean that Crosshairs and Guy extend the Methods class? I think that you have two classes, Guy and Crosshairs, which both extend the Methods class. They both inherit the "shoot" variable. However, it's an instance variable and so there is a separate copy of the variable for each actor instance. If you set the variable in a Crosshairs instance, it has no effect on the variable in a Guy instance. To get the behavior you want, you need the actors to communicate with each other. See tutorial #7.
wafflepudding wafflepudding

2013/1/29

#
That absoutely makes sense. And it worked! Thanks both of you!
You need to login to post a reply.