Hello,
I am new to Unity and a beginner at programming. I am playing around with Unity to create an RTS control scheme. The script is supposed to detect when the player right-clicks a position, after which the player’s unit should rotate to face in the direction of the click, and once it has finished rotating, it begins moving towards it. After following several tutorials and searching forum posts, I have been able to implement it through a Quaternion.Slerp within a coroutine loop. Problem is, once the ship is facing the correct direction, it doesn’t move.
Here is the code:
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
public class PlayerController : MonoBehaviour
{
public Camera cam;
public NavMeshAgent agent;
[SerializeField]
private float rotationSpeed = 0.3f;
private Vector3 moveOrder;
private Quaternion targetDirection = default;
private RaycastHit hit;
private bool isRotating;
private void Start()
{
agent.updateRotation = false;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
StartCoroutine(rotateShip(transform.rotation, targetDirection));
if (isRotating == false)
{
agent.SetDestination(hit.point);
}
}
}
}
IEnumerator rotateShip(Quaternion currentRotation, Quaternion targetDirection)
{
isRotating = true;
while (currentRotation != targetDirection)
{
targetDirection = Quaternion.LookRotation(hit.point - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetDirection, rotationSpeed * Time.deltaTime);
yield return 1;
}
isRotating = false;
}
}
The script seems to be stuck in the coroutine loop because the while loop condition is never met (i.e. currentrotation != targetRoation).
I saw this tutorial for calculating angles in unity, and tried my hand at implementing something similar: calculate the angle using the Inverse Tangent as shown in the video (except using the y axis for rotation instead of z, since my game uses 3D coordinates), then change the condition of the loop so it stops once the angle is acute enough. The code didn’t work, it would always output a negative right angle “-90.” I also tried my hand at Quaternion.Angle, but I couldn’t wrap my head around it.
I would appreciate if someone could shed some light into how to go about solving this. I am not just interested in a solution but in developing the thinking process to troubleshoot this sort of thing myself in the future. Thank you in advance!