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

2016/6/1

Saving specific coordinates of a moving object

SweetCaroline36 SweetCaroline36

2016/6/1

#
How do you save a specific x and y coordinate from a moving object? As in, I want variables to represent the x and y of one point along a line of an object as it moves. GetX() and getY() don't work because they are constantly being updated to match the object's current position. I need for coordinates to be saved with the click of a button without the movement being affected.
SPower SPower

2016/6/1

#
If you only want one pair of values for x,y to be saved, you can create two instance variables:
1
private int x, y;
If you'd like to have multiple values saved, creating an array would be the best way to go:
1
private int[] x, y;
which you'll have to initialise to the size you want (which will be how many values you want to be able to store).
SPower SPower

2016/6/1

#
With the array solution, it would make matters easier to add a 'counter' which says how many values have been stored:
1
private int count;
When 'saving' a location, you would then increase this by 1:
1
2
3
4
5
6
7
8
private void saveCurrentLocation()
{
    if (count <= limit) { // fill in a number for limit
        x[count] = getX();
        y[count] = getY();
        count++;
    }
}
This you could then modify to, for instance, overwrite previous stored locations if the limit is exceeded (e.g., a limit of 5, and when count is 5, you set it back to 0 so it starts to overwrite previous ones).
danpost danpost

2016/6/1

#
SPower wrote...
If you only want one pair of values for x,y to be saved, you can create two instance variables:
1
private int x, y;
With this, you can use 'getX()' and 'getY()' to set the values of 'x' and 'y' when a button is clicked:
1
2
3
4
5
if (Greenfoot.mouseClicked(null))
{
    x = getX();
    y = getY();
}
You need to login to post a reply.