I'm trying to make my player move towards mouse click using A* Pathfinding but I'm having some odd issues that I can't solve.
One of the issues is that player is moving a little bit even though it arrives at the position of the other transform
The second one is that the force is that is applied to the player is not constant, I would like it to keep always the same movement speed. I've tried to change to use transform.Translate to move the player with constant movement speed but it makes the movement to be like walk a little then stop, walk a little then stop...
This is the code that I'm using
using System;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
[SerializeField] private float speed = 100;
[SerializeField] private Text lifeText;
[SerializeField] private int life;
[SerializeField] private GameObject target;
[SerializeField] private float nextWaypointDistance = 3f;
//AI configurations
private Path path;
private Rigidbody2D rigidbody;
private Seeker seeker;
private int currentWaypoint = 0;
private bool reachedEndOfPath = false;
// Start is called before the first frame update
void Start()
{
seeker = GetComponent<Seeker>();
rigidbody = GetComponent<Rigidbody2D>();
InvokeRepeating("UpdatePath", 0f, .2f);
}
// Update is called once per frame
void Update()
{
lifeText.text = "Vida: " + life.ToString();
if (Input.GetMouseButtonDown(1)) //right click
{
Vector2 mousePos = Input.mousePosition;
Vector2 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
target.transform.position = worldPos;
}
}
private void UpdatePath()
{
if (seeker.IsDone())
seeker.StartPath(rigidbody.position, target.transform.position, OnPathComplete);
}
void FixedUpdate()
{
if (path == null) return;
if (currentWaypoint >= path.vectorPath.Count)
{
reachedEndOfPath = true;
return;
}
else
{
reachedEndOfPath = false;
}
Vector3 direction = (path.vectorPath[currentWaypoint] - (Vector3)rigidbody.position).normalized;
Vector3 force = direction * speed * Time.deltaTime;
rigidbody.AddForce(force);
float distance = Vector2.Distance(rigidbody.position, path.vectorPath[currentWaypoint]);
if (distance < nextWaypointDistance)
{
currentWaypoint++;
}
}
private void OnPathComplete(Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
}
What I want to is to make the movement smoother and with constant movement speed.
Can you guys help me?