Getting the reference to the player can be handled in different ways. You can maintain a reference to it in a field (preferable if your enemy will always chase the player) or you can locate it by using 'getObjectsInRange' (preferable if your enemy only chases the player when it is near the enemy).
I need PlayerPink to chase PlayerBlue just like if the computer had logic.That is my code
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
public class PlayerPink extends PlayerBlue
{
private GreenfootImage pink = new GreenfootImage("PinkPlayer.jpg");
int lastMovement = Greenfoot.getRandomNumber(4);
int newMovement = lastMovement;
public void act()
{
turnTowards(PlayerBlue.getX(), playerBlue.getY());
moveTron();
die();
leaveTrail(getX(), getY());
}
I get the error non-static method get(X) cannot be referenced from a static context.
Nah,I still get the same error..I changed the code to this
public void act()
{
Actor PlayerPink = (Actor)getWorld().getObjects(PlayerBlue.class).get(0);
turnTowards(PlayerPink.getX(), PlayerPink.getY());
moveTron();
die();
leaveTrail(getX(), getY());
}
But PlayerPink does not follow the Blue one again
The minor problem is that you are using 'PlayerBlue.getX()' instead of 'playerBlue.getX()'.
The major problem is that you have the PlayerPink class extending the PlayerBlue class. They should probably both extends Actor. Think of it this way: a PlayerPink object is NOT a PlayerBlue object, nor is the latter an object of the first type. Therefore, neither should extend the other. Both create Actor object, so they can both extend Actor. Both are player objects and you can add a Player class that extends Actor that both of these classes can extend.
In your PlayerPink class, add a field to hold the PlayerBlue object -- private PlayerBlue playerBlue;. Then, add the following method to that class:
public void setPlayerBlue(PlayerBlue pb)
{
playerBlue = pb;
}
Then, in your world class constructor (or a method it calls), when you are creating the actors and adding them into the world, declare a local fields to hold the players -- PlayerBlue pb = new PlayerBlue(); and PlayerPink pp = new PlayerPink();. Now, you can just call the new method with pp.setPlayerBlue(pb);. Once all this is done, you can then use playerBlue.getX() and playerBlue,getY() in the act method of the PlayerPink class.
You were probably trying to declare the field inside a method. Move it (private PlayerBlue playerBlue;) outside the method; but, keep it within the class.