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

2017/4/25

Help aiming at a moving player

jordanmyer jordanmyer

2017/4/25

#
I want the bad guy to fire a laser at the user controlled player's location. The bad guy is class Boss. This is the method that I have in Boss to try and fire a laser at the player.
public void fire(){
        Greenfoot.playSound("Laser.wav");
        
        Laser laser = new Laser();
        getWorld().addObject(laser, getX(), getY());
        laser.turnTowards(Player.getX(), Player.getY());
       
    }
However when I try to compile I get the error "non-static method getX() cannot be referenced from a static context. Any help would be welcome.
danpost danpost

2017/4/25

#
You are calling the 'getX' and 'getY' methods on a Class object, not on an object of the class. Player is the name of one of your classes, it does not refer to that which was created from the class, which is what has an x- and y-coordinate value in the world. You need to get the objects in the world of that class, if any, and then get the coordinates of it:
if (!getWorld().getObjects(Player.class).isEmpty()) // if any player in world
{
    Actor player = (Actor) getWorld().getObjects(Player.class).get(0); // get reference to first (and only) player in list
    laser.turnTowards(player.getX(), player.getY()); // turn laser towards player
}
// possible 'else' to maybe fire at a random location in world
You need to login to post a reply.