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

2015/4/15

How to make class that can find closest class

Dudeson Dudeson

2015/4/15

#
So I want to make class (that will be in the world) and could find closest class to himself. Let's say I want lemon to get closest object to lemon and get x and y coordinates, get id because there is 3 same class objects so they has their own id like 0 , 1 and 2 . is is possible to write something like this ?Could someone show me and example ? waiting for answer, Thanks
danpost danpost

2015/4/15

#
The 'getObjectsInRange(750, Ball.class)' method of the Actor class will return a list of objects of the specified class within the given range. You can iterate through the list and determine the closest one to the lemon. You could, as an alternative, use 'getWorld()'getObjects(Ball.class)' to get a list of all Ball objects in the world:
Actor closest = null; // to hold closest ball, if any
int closeness = 0; // how close closest ball found so far is
for (Object obj : getWorld().getObjects(Ball.class)) // for each ball in world (as Object object)
{
    Actor ball = (Actor) obj; // cast as Actor object
    int distance = (int)Math.hypot(ball.getX()-getX(), ball.getY()-getY()); // get distance
    if (closest == null || distance < closeness) // if first ball or closer ball
    {
        closest = ball;
        closeness = distance;
    }
}
if (closest == null) return; // if no balls
int closestX = closest.getX();
int closestY = closest.getY();
Dudeson Dudeson

2015/4/15

#
Thanks! do you know how to get class id ? like there are few same classes how to know what id is it ?
danpost danpost

2015/4/15

#
You could cast the 'closest' object to its class and call a getter method for it or access it directly if it is public.
Ball ball = (Ball) closest;
// if 'id' field is not 'public' and you have a 'public int getID()' method
int ballID = ball.getID();
// or if 'id' field is 'public'
int ballID = ball.id;
Dudeson Dudeson

2015/4/15

#
Thanks for quick and informative response !
You need to login to post a reply.