Using RotateTowards to turn a ship to a selected point-FIXED!

I cannot seem to make use of the RotateTowards function.

The idea at this point is to select the ship with a left click, and then with a right click set a destination. Eventually I would like to have it move to the point, but right now I’d be happy to just have it turn in place towards it.

I use multiple scripts in this (mostly a camera based on and this that handles the AI for a player ship) I can verify that mouseclick points are properly getting receieved to this script.

public class scr_AI_capShip : MonoBehaviour {
public GameObject thisShip;
public float turnRate;

private Vector3 destination;
private Vector3 location;
private Vector3 the_return;
private bool can_move = false;

// Use this for initialization
void Start () {
	destination = Vector3.zero;
}

public void setMoveTarget(Vector3 i) {
	destination = i;
	Debug.Log("Destination: " + destination);
	can_move = true;
}

// Update is called once per frame
void Update () {
	if (can_move) {
		location = thisShip.transform.localPosition;
		the_return = Vector3.RotateTowards(location, destination, Mathf.Deg2Rad*turnRate, 0);
		thisShip.transform.eulerAngles = new Vector3(the_return.x, the_return.y, the_return.z);
	}
}

}

Please tell me what I’m doing wrong…I feel that once I breach this knowledge barrier, I can do so much more.

UPDATE:

It works! There seems to be a little issue with where the model is pointing in relation to transform.forward but it works!!!

Thank you!

Here is the code in the relevant section:

	void Update () {
	if (can_move) {
		desired = destination - thisShip.transform.position;
		the_return = Vector3.RotateTowards(thisShip.transform.forward, desired, 
			Mathf.Deg2Rad*turnRate*Time.deltaTime, 1);
		thisShip.transform.rotation = Quaternion.LookRotation(the_return);
	}
}

You’re almost there- just a few details.

For starters, ‘location’ should be

location = thisShip.transform.position;

You don’t want to use localPosition for this (especially if the ship doesn’t have a transform parent).

Secondly, Vector3.RotateTowards returns the vector pointing forwards. Try using Quaternion.LookRotation with it:

thisShip.transform.rotation = Quaternion.LookRotation(the_return);

Finally, having ‘0’ as either the maxRadiansDelta or the maxMagnitudeDelta will prevent the rotation from working. Make sure both of these are over 0.

EDIT:

Looks like there was something else, too.

See, RotateTowards is like Lerp in that it takes two paramaters, the current direction, and the desired end direction. What you are giving it right now are the two positions- the position of the ship and the position of the target. Of course, such a thing requires feedback to function properly- you should change it to this:

Vector3 desiredDirection = destination - location;
the_return = Vector3.RotateTowards(transform.forward, desiredDirection,
    Mathf.Deg2Rad*turnRate*Time.deltaTime, 1);