I have an odd problem that I can’t seem to figure out. I’m using a right-click to move an object and everything is working at it should for the most part. When the object reaches the target it keeps moving/flipping. I’m sure it’s something simple and I’ve just been looking at it too long. Any help would be appreciated.
To set the point, in another script I used :SetMovePosition(Camera.main.ScreenToWorldPoint(Input.mousePosition))
MovePositionPathfinding
public class MovePositionPathfinding : MonoBehaviour
{
public Vector3 movePosition;
private Vector3 moveDir;
private void Start()
{
}
// Update is called once per frame
void Update()
{
moveDir = (movePosition - transform.position);
float dist = Vector3.Distance(movePosition, transform.position);
GetComponent<MoveVelocity>().SetVelocity(moveDir.normalized);
//Debugging
EDebug.TextUpdater( () => movePosition.ToString() + " - " + transform.position.ToString() + " = " + moveDir.ToString() , new Vector3(10f,40f, 1f));
}
public void SetMovePosition(Vector3 movePosition)
{
this.movePosition = movePosition;
}
public void RandomPosition()
{
Vector3 tempPos = Random.insideUnitCircle*20;
SetMovePosition(tempPos.normalized);
}
}
MoveVelocity
public class MoveVelocity : MonoBehaviour
{
[SerializeField] private float moveSpeed;
private Rigidbody2D rigidbody2d;
private Vector3 velocityVector;
private void Awake()
{
rigidbody2d = GetComponent<Rigidbody2D>();
}
public void SetVelocity(Vector3 velocityVector)
{
this.velocityVector = velocityVector;
}
private void FixedUpdate()
{
HandleRotation();
rigidbody2d.velocity = velocityVector * moveSpeed;
}
private void HandleRotation()
{
Vector2 vectorToTarget = rigidbody2d.velocity;
if (vectorToTarget != Vector2.zero)
{
transform.LookAt(transform.position + new Vector3(0, 0, 1), vectorToTarget);
}
}
The numbers on screen are on line 18 of the MovePositionPathfinding.