- Home /
Need an advice: 2D A* Pathfinding + Move to click
Hello! I started using A* Pathfinding Project assets in my new prototype and I want character moves by mouse click.
The first idea I implemented: 1. Create target which is at the middle of the player by default. 2. When I perform mouse click target position value changes according to click coordinates 3. Player moves to the new target position 4. When player reaches the target he stops
private Vector2 targetPosition;
private GameObject target;
void Start()
{
target = GameObject.FindGameObjectWithTag("Target");
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.transform.position = targetPosition;
}
}
I got two problems with this solution: I'm not applying force to the player's Rigidbody2D which is kinda strange and gives less data to further development, I suppose (for example for defining speed ect.).
The second problem is that when I add Rigidbody to the Player and while moving his path he meets a collider, he gets stuck or start rotating.
I didn't find any tutorial which explains "A* Pathfinding" and "Click to move" combined. Could somebody please help on this?
Answer by rh_galaxy · Feb 07, 2020 at 01:48 PM
I don't see where you have the A* algorithm called and implemented. Seems you just set the transform directly to the coordinate of the mouse every frame...
A* is used to do the shortest path in a 2D grid where all cells have a cost to pass or is impassable... You need to implement/divide your world into that grid yourself... however it may fit to do in Unity and your obstacle objects...