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

2012/4/7

Object moving from one spot to another continually

Alfie5 Alfie5

2012/4/7

#
I can get my object to move to a location using setlocation but how would I then get it to gack where it came from and then continue to do this? So an object starts at location 'a' jumps to location 'b' then back to 'a' then back to 'b' in a continous loop?
SPower SPower

2012/4/7

#
You just have to save the x and the y of location a and b in your world. Then your object needs to acces them and move to them. Something like this:
private int aX;
private int aY;
private int bX;
private int bY;

.. some other code...

public int getAX() {
return aX;
}
public int getAY() {
return aY;
}
public int getBX() {
return bX;
}
public int getBY() {
return bY;
}
And then your object simply has to use those methods and move to them
danpost danpost

2012/4/8

#
Another way is by saving just the other location (the one it is not at). I will call your object a 'Teleporter': Use
addObject(new Teleporter(nextX, nextY), currentX, currentY);
to add the object to the world (nextX, nextY, currentX, and currentY need to be set to the coordinates of the two points the object teleports between). The 'Teleporter' class needs a constructor to receive the two coordinates sent to it; so, this code would go in the 'Teleporter' class:
//the following variables will hold to coordinates of the other location
private int otherX = 0;
private int otherY = 0;
// the following constructor receives and saves the location to teleport to
public Teleporter(int inX, int inY)
{
    otherX = inX;
    otherY = inY
}
// the following method teleports the object and saves the next location to teleport to
public void switchLocations()
{
    int oldX = getX();
    int oldY = getY();
    setLocation(otherX, otherY);
    otherX = oldX
    otherY = oldY;
}
When you want it to change locations, call the 'switchLocations()' method (from the act method when the trigger occurs, or from another class). @SPower, it is always better to have code related to one type of object in that object's class code, even if the actor was the main actor in the scenario (otherwise, you clutter up the world class code with stuff and make it hard to read).
You need to login to post a reply.