Rotating to target

Hi,

I have made a Seek class, which is used for an Entity to follow another Entity.
Seek is derived from Behaviour, which contains a getSteering() method that returns the change in velocity and rotation the character has to make to seek its target.

This is what SteeringOutput looks like. The rotation is in euler angles.

public struct SteeringOutput
{
	public Vector3 linearVel; // linear velocity	
	public Vector3 rotation; // euler angles
}

This is the Seek class:

public class Seek : Steering
{
	public Entity character;
	public Entity target;
	public float speed;
	
	// constructor
	public Seek(Entity _character, Entity _target, float _speed)
	{
		character = _character;
		target = _target;
		speed = _speed;
	}
	
	public SteeringOutput GetSteering()
	{
		SteeringOutput steering = new SteeringOutput();
		
		// get the direction to the target
		steering.linearVel = target.Transform().position - character.Transform().position;
		
		// the velocity is along this direction, at full speed
		steering.linearVel.Normalize();
		steering.linearVel *= speed;
		
		// face in the direction we want to move
		steering.rotation = Quaternion.FromToRotation(character.Transform().forward, steering.linearVel).eulerAngles;
		
		return steering;
	}
}

As you can see I use the FromToRotation method from Quaternion to calculate the angle required to turn from the characters current facing to its target facing. But it seems that something is wrong, because the character is looking at a wrong direction and rotates around itself.
By the way, it follows the target correctly, only the rotation is wrong.

The character class uses it like this:

// Update is called once per frame
	void Update()
	{
		var steering = behaviour.GetSteering();
		
		transform.position += steering.linearVel * Time.deltaTime; // update position
		transform.eulerAngles += steering.rotation * Time.deltaTime; // update rotation
	}

I am doing something wrong with the rotation, but I don’t understand what.

1353999--66883--$2r74zlg.png

The first thing you should do is stop using Euler angles for your main calculations. You can use them to define orientations in a user-friendly manner, but converting quaternions back into Euler angles is worth avoiding unless you really need it - and “transform.eulerAngles” is doing just that. Line 27 of your Seek class is also performing this kind of conversion.

Make your Steering class store a quaternion for the rotation, then in your Update method you can use Quaternion.RotateTowards (or similar) to move transform.rotation (instead of transform.eulerAngles) steadily towards that orientation.

You may find this fixes the problem but if not then I’d suggest posting the updated code and asking for additional assistance.

Also take a look at Unity - Scripting API: Transform.LookAt