Object can't get to the target point
2D game, movement on the x, y axes, rotation around the z axis. I get the mouse coordinates, transform them into world coordinates. Then the ship begins to rotate smoothly and move to the point of mouse click. Each time the ship does not get exactly in the position of the point and begins to rotate around it!
public class RotateMoveToPoint : MonoBehaviour
{
private Vector3 targetPosition; // Mouse Click position
public float moveSpeed = 2.0f; // Ship speed
public float turnSpeed = 180.0f; // Ship turn speed
private bool isMoving = false; // Ship is in a movement?
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPosition.z = 0;
Debug.Log(targetPosition);
isMoving = true;
}
if (isMoving)
{
Debug.DrawLine(transform.position, targetPosition, Color.red);
Quaternion newRotation = Quaternion.LookRotation(transform.position - targetPosition, Vector3.forward);
// Blocks rotation around the x, y axis
newRotation.x = 0f;
newRotation.y = 0f;
transform.rotation = Quaternion.RotateTowards(transform.rotation, newRotation, turnSpeed * Time.deltaTime);
transform.Translate(Vector3.up * moveSpeed * Time.deltaTime, Space.Self);
// transform.position += transform.up * moveSpeed * Time.deltaTime;
if (transform.position == targetPosition)
{
isMoving = false;
}
}
}
}
Additional check doesn't help. Because if the point is next to the ship, the result is that the ship still rotates around it!
if ((transform.position - targetPosition).magnitude < 0.1f)
@Shadowsektor It looks like you're not catering for the ship overshooting its position. Try using the Vector3.$$anonymous$$oveTowards function ins$$anonymous$$d to see if it solves your issue. In addition, try not to set is$$anonymous$$oving
to true on mouse clicks if the ship is already at the targetPosition to begin with, as that would cause an unnecessary rotation or possible error due to the LookRotation
position delta being Vector3.zero.