itsmetheperson
itsmetheperson

Reputation: 77

Following a path in LibGdx

I've got code that's outputting a path in libGdx:

public Target(Vector2 villager, Vector2 target){
      pathFinder = new IndexedAStarPathFinder<Node>(LevelManager.graph, false);

        int startX = (int) villager.x;
        int startY = (int) villager.y;

        int endX = (int) target.x;
        int endY = (int) target.y;

        Node startNode = LevelManager.graph.getNodeByXY(startX, startY);
        Node endNode = LevelManager.graph.getNodeByXY(endX, endY);

        pathFinder.searchNodePath(startNode, endNode, new HeuristicImp(), resultPath);
        Gdx.app.log("Path", ""+ resultPath.getCount());

  }

My question is, is there a way of then using the resultPath to implement movement without using steering behaviors? Something simple to grasp and implement? I'm talking about moving the x and y of a sprite in accordance to the outputted path. Help would be appreciated!

Upvotes: 3

Views: 1443

Answers (1)

m.antkowicz
m.antkowicz

Reputation: 13571

You just need to move your sprite from it's currentPosition to the nextPosition - you can store these values in Vector2 class instances.

You will be updateing sprite's position in your render() method like

    Vector2 currentPosition, nextPosition;
    final float SPEED; //how fast sprite will be moved

    //render()
    Vector2 step = nextPosition.cpy().sub(currentPosition).nor().scl(SPEED);
    sprite.setPosition(sprite.getX() + step.x, sprite.getY() + step.y);

then you have to check whether your sprite achieved nextPosition (or rather if it's distance of it is small enough) and if yes you must set new nextPosition value

    if(nextPosition.cpy().sub(sprite.getX(), sprite.getY()).len() < SOME_LENGTH) {
        nextPosition = getNextPosition();

If no new nextPosition is to get then the new nextPosition value should be just sprite's position (to keep it in place)

Upvotes: 1

Related Questions