2D pathfinding unity game

Hey there,

I am trying to make a 2D game using Unity. I want to move the character on click using A* Pathfinding. When I start my scene the player moves to the target but if I move the target nothing happens…

How to trigger the pathfinding when the target changes the position?

  1. List item

Hi

What movement script are you using?
In the included example scenes there are a few that are configured to make the AI move to the target only when double-clicking.

Hey thanks for the replay!
I changed it a bit and I am not getting it to work… The thing is there are not many tutorials on the web and i am pretty new.
If I get this done I can finally start with the other things :slight_smile:

My movment code looks like this at the moment


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;

public class PlayerMovment : MonoBehaviour {
public Transform targetPosition;

private Seeker seeker;
private CharacterController controller;
private GameObject player;
public Camera cam;


public Path path;
public float speed = 2;
public float nextWaypointDistance = 3;
private int currentWaypoint = 0;
public bool reachedEndOfPath;
public Vector3 playerPosition;

public void Start()
{
    seeker = GetComponent<Seeker>();
    controller = GetComponent<CharacterController>();
    cam = GetComponent<Camera>();
    // If you are writing a 2D game you can remove this line
    // and use the alternative way to move sugggested further below.


    // Start a new path to the targetPosition, call the the OnPathComplete function
    // when the path has been calculated (which may take a few frames depending on the complexity)

}

public void OnPathComplete(Path p)
{
    Debug.Log("A path was calculated. Did it fail with an error? " + p.error);

    if (!p.error)
    {
        path = p;
        // Reset the waypoint counter so that we start to move towards the first point in the path
        currentWaypoint = 0;
    }
}
public void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Vector3 mousePos = Input.mousePosition;
        Debug.Log(mousePos);
        
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        Debug.Log(ray);
        if (Physics.Raycast(ray, out hit))
        {
            seeker.StartPath(transform.position, hit.point, OnPathComplete);
        }
    }
    if (path == null)
    {
        // We have no path to follow yet, so don't do anything
        return;
    }



    //Debug.Log(playerPosition);

    // Check in a loop if we are close enough to the current waypoint to switch to the next one.
    // We do this in a loop because many waypoints might be close to each other and we may reach
    // several of them in the same frame.
    reachedEndOfPath = false;
    // The distance to the next waypoint in the path
    float distanceToWaypoint;
    while (true)
    {
        // If you want maximum performance you can check the squared distance instead to get rid of a
        // square root calculation. But that is outside the scope of this tutorial.
        distanceToWaypoint = Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]);
        if (distanceToWaypoint < nextWaypointDistance)
        {
            // Check if there is another waypoint or if we have reached the end of the path
            if (currentWaypoint + 1 < path.vectorPath.Count)
            {
                currentWaypoint++;
            }
            else
            {
                // Set a status variable to indicate that the agent has reached the end of the path.
                // You can use this to trigger some special code if your game requires that.
                reachedEndOfPath = true;
                break;
            }
        }
        else
        {
            break;
        }
    }

    // Slow down smoothly upon approaching the end of the path
    // This value will smoothly go from 1 to 0 as the agent approaches the last waypoint in the path.
    var speedFactor = reachedEndOfPath ? Mathf.Sqrt(distanceToWaypoint / nextWaypointDistance) : 1f;

    // Direction to the next waypoint
    // Normalize it so that it has a length of 1 world unit
    Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
    // Multiply the direction by our desired speed to get a velocity
    Vector3 velocity = dir * speed * speedFactor;

    //// Move the agent using the CharacterController component
    //// Note that SimpleMove takes a velocity in meters/second, so we should not multiply by Time.deltaTime
    //controller.SimpleMove(velocity);

    // If you are writing a 2D game you may want to remove the CharacterController and instead use e.g transform.Translate
    transform.position += velocity * Time.deltaTime;
}

}

That code doesn’t really fit with what you are saying above.
You say that the agent moves to the target when just starting the scene, but you never recalculate the path unless the mouse is clicked.