views:

130

answers:

3

To illustrate I currently have something like

int startX,endX,currX;
int startY,endY,currY;

public void updatePos(){

if(currX<=endX){
   currX+=1;
}
//Same for y

I can see that I dont want to move x and y the same amount each time but dont know how to work out what I should do to determine how much each should be adjusted.

Any ideas

Maybe this will help clarify

Imagine I start at these coords (0,0) and I want to get to (18,10)

if I increment my x and y until they reach the desired target by a step of one the sprite moves diagonnally upwards then across the screen to the right before resting in the correct position.

The behaviour I want is that it travels a single direction towards the destination point (along the splope of a triangle if you will)

Im looking for suggestions on how to find my next set of points

A: 

Typically you will have a required velocity for your sprite and will update its position based on its velocity and the time ellapsed since it was last updated, e.g.

public class MySprite {
  int x, y; // Location
  int dx, int dy; // Velocity in pixels / millisecond

  public void updatePosition(long deltaMillis) {
    // Update x and y position based on current velocity.
    x += dx * deltaMillis;
    y += dy * deltaMillis;
  }
}

Depending on the speed of your machine your animation loop will run faster or slower. However, as your updates are based on a pre-specified velocity this will not affect the speed of the sprite moving across the screen.

public void animationLoop() {
  long prev = System.currentTimeMillis();; 
  long now;
  long deltaMillis;

  while (animationRunning) {
    // Record ellapsed time.
    now = System.currentTimeMillis();
    deltaMillis = now - prev;
    prev = now;

    if (deltaMillis > 0L) { // Some time has passed so move sprite.
      sprite.updatePosition(deltaMillis);
    }

    // TODO: Repaint sprite.
  }
}
Adamski
does that tell me where it will fall on a path: what Im getting at is imagine travelling up the slope of a triangle how can i get the points on the slope
allen
When you say the points on the slope do you mean every point that makes up the line? The code above won't do this as the sprite is being moved in discrete time-steps causing it to "jump" a few pixels at a time. Each location of the sprite *will* lie on the slope but it will not visit every single point. Can you expand your question describing what you're trying to achieve? ... i.e. Is this an animation problem or more geometry related?
Adamski
+2  A: 

If T is the time that is needed to move from X0,Y0 to X1,Y1, the position at any given time t (0 <= t <= T) is:

X = X0 + t*(X1-X0)/T
Y = Y0 + t*(Y1-Y0)/T
Maurice Perry
A: 

Based on your expanded question it sounds like you're interested in visiting every pixel between the start and end location. In this case you might want to take a look at Bresenham's Line Algorithm, which describes how to do this.

Adamski