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

2020/12/1

Having trouble with referencing actors because static/non-static issues

Hissss Hissss

2020/12/1

#
Hello, I'm fairly new to Greenfoot and have been trying to get an enemy to follow the main character, kara, when in a certain radius for the past two hours with no luck. Is there any chance someone can help me out? Here's the code for the main character that is relevant: public int returnX(){ return getX(); } public int returnY(){ return getY(); } public int returnAngle(){ return getRotation(); } And here's what I have for the enemy as of now that is relevant: public void act() { moveAndTurn(); touch(); } public void moveAndTurn(){ turnTowards​(kara.getX(), kara.getY()); move(1); } This is definitely some fundamental understanding that I don't understand so I'm hoping someone can help me out. Thanks!
danpost danpost

2020/12/1

#
Hissss wrote...
This is definitely some fundamental understanding that I don't understand so I'm hoping someone can help me out. Thanks!
A class (e.g. kara) describes an object . Any number of objects can be created from a class such as kara. These objects, when Actor objects, can have location coordinates in a world. Saying "kara.getX()" does not specify which object created from the class that you want the coordinate of. Another way to look at it is that kara is a class name -- not an Actor object and class names do not have coordinates in any world. One way to get a reference to the kara object in your world is:
Actor k = getWorld().getObjects(kara.class).get(0);
However. you seem to require the kara object to be within some range, so you could use (replacing "<< range >>" with the proper value or variable):
Actor k = null;
if (getObjectsInRange(<< range >>, kara.class).size()  > 0)
{
    k = getObjectsInRange(<< range >>, kara.class).get(0);
}
if (k != null)
{
    // put follow code here
}
You can now get the coordinates of the kara object for the follow codes with this:
int karaX = k.getX();
int karaY = k.getY();
Hissss Hissss

2020/12/1

#
I saw you in a bunch of other posts and want to thank you so much for the speedy reply! I have a major progress check due tomorrow and you saved my life! Thank you so much Mr. Danpost! I can't imagine how many other people you helped save and hope this message goes to heart because I'll likely be needing your help some more sometime in the future.
You need to login to post a reply.