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

2016/5/23

How do I get the postion of an object in Greenfoot?

Michael1000 Michael1000

2016/5/23

#
Hello, I have created an object, which is suppoosed to travel to the edge of the map, after which it would disappear. The way of doing this that I tried was to check if the coordinates of the object pass the edges of the map, and if so the object would be deleted. I am using the getY and getX methods, but the computer returns the error: "cannot find symbol variable projectile". Is there a better way to do this, or how can I fix the above problem, oh here's the code: public void act() { move(10); if (projectile.getX > 400 || projectile.getY < 0) { getWorld().removeObject(this); } }
danpost danpost

2016/5/23

#
A few things here: (1) to refer to the object being worked on by the 'act' method (or any other non-static method within a class on an object created from that class or any subclass of that class), use the 'this' keyword; so, instead of 'move(10);', you could use 'this.move(10);'; and instead of 'projectile.getX()', you could use 'this.getX()' or just 'getX()' (as 'this' is understood when no object is given to execute a non-static method on). (2) when using the standard 'super' call to create a World object, the world is made a bounded one -- meaning that no object can have a coordinate value of less than zero or greater than or equal to the width (or height) of the world; therefore, you should check for at edge instead of beyond edge; (3) method calls must always have a set of round brackets (parenthesis) following the name -- 'getX' should be 'getX()' and 'getY' should be 'getY()'; neither of these requires any additional information to execute and the contents between the brackets remains empty; however, for those methods that require more information, such as the 'removeObject' method of the World class, the object to be removed must be given and is included between the brackets; (notice the use of 'this' to refer to the projectile here). So, what you should have is this:
1
2
3
4
5
6
7
8
public void act()
{
    move(10);
    if (getX() == 399 || getY() == 0)
    {
        getWorld().removeObject(this);
    }
}
One more thing here is that I doubt very much if you want to check for being at the right and top edges of the world window as the condition of the 'if' statement suggests. You may want to re-think what you want there.
You need to login to post a reply.