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.