I have this enemy class, and I want it to
1) Spawn at a certain place Vector3 pos
2) Rotate to face my player position
3) Move forward
As this code is now, it will appear at it's specified place: pos
, and attempt to rotate to face it's target: targetShip
. It fails to correctly face it's target, because of this offset.
If I remove the code that assigns a value to translation
, or if I normalize pos
then the model will appear at the origin and rotate to face it's target correctly.
If I try to move it at all using any of the comment out code regarding translation
, It appears to start someplace else and I never can find it.
However, if I remove the code relating to rotation
, and uncomment the code relating to translation
, then I can get it to move forward.
The trick is doing it all together.
class Enemy : BasicModel
{
Matrix rotation = Matrix.Identity;
Matrix translation = Matrix.Identity;
public Vector3 pos, up, right, targetShip,dir;
public Enemy(Model m, Vector3 pos)
: base(m)
{
up = Vector3.Up;
//sets the position to the Vector3 as it's spawn point.
translation = Matrix.CreateTranslation(pos);
}
public override void Update()
{
//Glo is a global class, where I store the player world.
targetShip = Glo.world.Translation;
targetShip.Normalize();
pos = transform.Translation;
rotation = RotateToFace(targetShip, pos, Vector3.Up);
//Attempt at moving the model forward. Causes it to go out of view
//translation *= Matrix.CreateTranslation(this.GetWorld().Backward);
//translation *= Matrix.CreateTranslation(pos);
}
public override Matrix GetWorld()
{
return rotation * world * translation ;
}
/*Params: O = Our target
* P = Our position
* U = up.
*
* Code from some site I googled up.
*/
Matrix RotateToFace(Vector3 O, Vector3 P, Vector3 U)
{
//The direction we're facing.
Vector3 D = (O - P);
//Our relative Right.
Vector3 Right = Vector3.Cross(U, D);
Vector3.Normalize(ref Right, out Right);
//Our back
Vector3 Backwards = Vector3.Cross(Right, U);
Vector3.Normalize(ref Backwards, out Backwards);
//Our relative up
Vector3 Up = Vector3.Cross(Backwards, Right);
//Make a matrix out of all of these.
Matrix rot = new Matrix(Right.X, Right.Y, Right.Z, 0, Up.X, Up.Y, Up.Z, 0, Backwards.X, Backwards.Y, Backwards.Z, 0, 0, 0, 0, 1);
return rot;
}
}
}
----
This is fixed now, and all this code is mostly obsolete.