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

2013/10/22

X-coords of a specific object

ddvink ddvink

2013/10/22

#
Hi all, In my world I have a couple of objects from my rope class of which a char can use to climb. He's able to climb, but it's still a litte fuzzy. So what i want to do, is setting the his X-value equal to the x-value of the object. How can I request the x-position of a specific object in my Char class. The class of the rope is not inherited with the char. Yours, Dennis de Vink
Gevater_Tod4711 Gevater_Tod4711

2013/10/22

#
Your char is probably touching the rope when he's climbing, so you can easily get a referenct to the rope using the getOneIntersectingObject(Class clss) method. Now if you got the reference to the object you can set the x coordinate of your char to the x coordinate of the rope:
public void climb() {
    Rope rope = (Rope) getOneIntersectingObject(Rope.class);
    
    setLocation(rope.getX(), getY());
}
SPower SPower

2013/10/22

#
Instead of getOneIntersectingObject, you can also use:
Rope rope = getWorld().getObjects(Rope.class).get(0);
Gevater_Tod4711 Gevater_Tod4711

2013/10/22

#
But this will only work if there is only one rope in the world. (Or you randomly choose the right one). Also if there is no rope in the world this will cause an IndexOutOfBoundsException.
SPower SPower

2013/10/22

#
@Gevater_Tod Good point!
danpost danpost

2013/10/22

#
Also, Gevater_Tod4711 gave code that could cause a NullPointerException if the char is not touching it. So, either way, you will need to perform a check (for a null value or for an empty list) before continuing with getting the reference from the list or using it to get the location of it ).
ddvink ddvink

2013/10/22

#
This worked well!!! Great work! thanks
SPower SPower

2013/10/22

#
Did you also improve it like danpost said?
You need to login to post a reply.