# Moving Platforms in Box2d in a Specified Path

Hi,

In one of the previous post we moved a platform from a point A to point B and then back to point A and so on. In this post we would expand on it and move it in specific path which has more than 2 points which we find in many platformers like mario etc.

It is similar to way we moved a platform in last post just in this case we would have more than 2 points in the path.

Path:

We would define a basic class which will hold the information of the path which the platform will travel over a period of time. There are many ways to do it. This is just one of them.

```public class Path{
ArrayList<Vector2>  positions;
ArrayList<Float> times;
Vector2 velocity;
int currentPointIndex;
int nextPointIndex;
int direction=1;
public Path(int count){
positions=new ArrayList<Vector2>();
times=new ArrayList<Float>();
velocity=new Vector2();

}
}

public void Reset(){
currentPointIndex=0;
nextPointIndex=GetNextPoint();
SetNextPointVelocity();
}

public Vector2 GetCurrentPoint(){
return positions.get(currentPointIndex);
}
public boolean UpdatePath(Vector2 bodyPosition){
return ReachedNextPoint(bodyPosition);
}
boolean ReachedNextPoint(Vector2 bodyPosition){
Vector2 nextPointPosition=positions.get(nextPointIndex);
float d=nextPointPosition.dst2(bodyPosition);
currentPointIndex=nextPointIndex;
nextPointIndex=GetNextPoint();
SetNextPointVelocity();
return true;
}
return false;
}

int GetNextPoint(){
int nextPoint=currentPointIndex+direction;
if(nextPoint==positions.size()){
nextPoint=0;
}else if(nextPoint==-1){
nextPoint=positions.size()-1;
}
return nextPoint;
}
void SetNextPointVelocity(){
Vector2 nextPosition=positions.get(nextPointIndex);
Vector2 currentPosition=positions.get(currentPointIndex);
float dx=nextPosition.x-currentPosition.x;
float dy=nextPosition.y-currentPosition.y;
float time=times.get(nextPointIndex);
velocity.set(dx/time,dy/time);
}

Vector2 GetVelocity(){
return velocity;
}
}```

The above can be used as a direction for making a kinematic body move through a specified path. We have to check in the update function of the object class (which is moving in the specified) that if  UpdatePath(bodyPosition) returns true then just set a new velocity to the body by calling GetVelocity().

MovingObject

``` ...
Path path;
public void Update(float dt){
.....
if(path.UpdatePath(bodyPosition)){
SetBodyVelocity(path.GetVelocity());
}
}```

We are passing position in update function of path so that it can be used with all types of moving objects and not specific to box objects.

Source Code:

We have attached a sample source code for the above – here.

For setting the example in eclipse please look for instructions in this post.

Thank you for the patience. If you have queries/suggestions please post them in comments section.

Tagged with: , , , ,