Reputation: 13
Please, help me with my issue. I need to move an Actor to dynamic coordinates of another Actor. If I use MoveToAction, the Actor moves to the given GetX() and GetY() coordinates of another Actor, but does not follow it as it moves.
This simple code move Actor to old coordinates of another Actor. I want the game element to follow the moving player.:
game_element = new GameContainer();
stage.addActor(game_element);
game_element.addAction(Actions.moveTo(player.getX(), player.getY(), 2));
But if I move the player at the moment when the game element moves to him, then he arrives at the old coordinates, and does not follow him. How can this be implemented in LibGDX?
Upvotes: 0
Views: 77
Reputation: 1158
Depending on the details of what you're after this can be achieved by creating your own Action
.
This example will try to get to the target Actor
at a constant speed, and the Action
is disabled when the followed reaches the target (but this can easily be changed by changing the behaviour of the act
method)
public class MoveToActorAction extends Action
{
private final Actor target;
private float speed = 140.0f; // this is how fast you want it to move
private float threshold = 1.0f; // this is how close it needs to be for you to consider it to be at the target
public MoveToActorAction(Actor target) {
this.target = target;
}
@Override
public boolean act(float delta) {
Vector2 position = new Vector2(actor.getX(), actor.getY());
Vector2 targetPosition = new Vector2(target.getX(), target.getY());
Vector2 directionToTarget = targetPosition.sub(position);
float distance = directionToTarget.len();
if (distance < threshold) {
return true; // it has gotten to the target
}
else {
float distanceToTravel = Math.min(distance, delta * speed);
position.add((directionToTarget.nor().scl(distanceToTravel)));
actor.setX(position.x);
actor.setY(position.y);
return false;
}
}
}
In the image below the T is the target and the F is the follower and the T has two sequenced actions moving it to two corners, and the F has only the MoveToActorAction
.
Upvotes: 2
Reputation: 36
create action to move two third of the distance,
Re calculate Target..
Put 1 and 2 in a sequence Action, add it to the one that chases..
Repeat 1-3 until you get closer.
void chasePlayer(){
xDistance = player.getX()-getX(); yDistance = player.getY()-getY();
int actualDistance = Mathutils.sqrt(xDistance^2 + yDistance^2);
if(actualDistance < distance_threshold){ Stop chasing player do target reached part }
timeForThisMove = actualDistance * 0.66f / mySpeed;
MoveByAction act1 = (Actions.moveBy(xDistance0.66f, yDistance0.66f, timeForThisMove));
Runnable reCalculateTarget = new Runnable() {
@Override
public void run() {
chasePlayer()
}
};
// This will set two actions in sequence.. chase 2/3rd and recalculating
game_element.addAction(Actions.sequence(act1, Actions.run(reCalculateTarget));
}
Upvotes: 0