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

2012/3/3

One object "chasing" another

tallyaka tallyaka

2012/3/3

#
I want a cyclops to run at you but I have no Idea where to start. I tried looking for a scenario and I found space chase. It's code is as follows:
   
    private Player target;

 public void faceTarget() 
    { //This command makes the ship face an actor.
        int xDiff = target.getX() - getX();
        int yDiff = target.getY() - getY();
        double angle = Math.toDegrees(Math.atan2(yDiff, xDiff));
        setRotation((int)Math.round(angle));
    }
but for me it says that it can't find type "player" Help?
Duta Duta

2012/3/3

#
2 things: First off, is there an actor sub-class called Player.class in your scenario? Secondly, is "lic void faceTarget()" supposed to read "public void faceTarget()"?
tallyaka tallyaka

2012/3/3

#
1. It is an Odysseus game and I did change all the occurrences of "Player" to "Odysseus." (when it was the class odysseus) 2. Yes, it is supposed to be public, copying problem sorry, fixing it right now.
Duta Duta

2012/3/3

#
1. If you've got "Odysseus" instead of "Player", have you changed it to "private Odysseus target"?
tallyaka tallyaka

2012/3/3

#
I thought it was a classifier. I did change it but it still doesn't work :( Here's my code now:
    public Polyphemus()
    {
        health = 20;
        setRotation(180);
        target = Odysseus;
    }
    private Odysseus target;
    public void faceTarget() 
    { //This command makes the ship face an actor.
        int xDiff = target.getX() - getX();
        int yDiff = target.getY() - getY();
        double angle = Math.toDegrees(Math.atan2(yDiff, xDiff));
        setRotation((int)Math.round(angle));
    }
It says "Cannot find Symbol - Variable Odysseus" for the one in the constructor.
Duta Duta

2012/3/3

#
Oh, it makes sense now. Change target = Odysseus to target = null, and then make faceTarget() into the following:
import java.util.List;
//==========
public void faceTarget()
{
	if(target == null)
	{
		if(!getWorld().getObjects(Odysseus.class).isEmpty())
		{
			target = getWorld().getObjects(Odysseus.class).get(0);
		}
	}
	if(target != null)
	{
		int xDiff = target.getX() - getX(),
			yDiff = target.getY() - getY();
		double angle = Math.toDegrees(Math.atan2(yDiff, xDiff));
		setRotation((int)Math.round(angle));
	}
}
tallyaka tallyaka

2012/3/3

#
It says Incompatible types in the 0 in line 9 of your code.
Duta Duta

2012/3/3

#
My bad - change line 9 of it to:
target = (Odysseus) getWorld().getObjects(Odysseus.class).get(0);
tallyaka tallyaka

2012/3/3

#
Ok, it's working. I'm publishing my "so far" version go here to check it out! p.s. Thanks a ton! Never would have figured all that out on my own.
You need to login to post a reply.