I have two objects (target and player), both have Position (Vector3) and Rotation (Quaternion). I want the target to rotate and be facing right at the player. The target, when it shoots something should shoot right at the player.
I’ve seen plenty of examples of slerping to the player, but I don’t want incremental rotation, well, I suppose that would be ok as long as I can make the slerp be 100%, and as long as it actually worked.
FYI – Im able to use the position and rotation to do plenty of other things and it all works great except this last piece I cant figure out.
EDIT
Code samples run in the Target’s class, Position = the targets position, Avatar = the player.
Using the value of 1 for the Slerp isn’t work. This code below rotates some, but I think something is way off becuase when it’s drawn the target scales up and then down as the player gets closer.
var A = new Vector3(Position.X, Position.Y, Position.Z);
var B = new Vector3(GameState.Avatar.Position.X, GameState.Avatar.Position.Y, GameState.Avatar.Position.Z);
A.Normalize();
B.Normalize();
var angle = Math.Acos(Vector3.Dot(A, B));
var axis = Vector3.Normalize(Vector3.Cross(A, B));
var rotOnAngle = new Quaternion(axis, (float)angle);
var newRot = Quaternion.Slerp(Quaternion.Identity, rotOnAngle, 1f);
Rotation = newRot;
Cannon.Shoot(Position, Rotation, this);
I tried using this and it doesn’t quite work either…the target does rotate, but not to face the player. But at least the scaling problem goes away.
Quaternion q = new Quaternion();
var pos = Vector3.Normalize(Position);
var pos2 = Vector3.Normalize(GameState.Avatar.Position);%
var a = Vector3.Cross(Position, GameState.Avatar.Position);
q.X = a.X; q.Y = a.Y; q.Z = a.Z;
q.W = (float)Math.Sqrt(((int)Position.Length() ^ 2) * ((int)GameState.Avatar.Position.Length() ^ 2)) + Vector3.Dot(Position, GameState.Avatar.Position);
q.Normalize();
Rotation = q;
Cannon.Shoot(Position, Rotation, this);
I happen to ask the same question over in Game Dev stack exchange and someone answered over there. Make sure to read the comments in the answer, regardless, the answer/solution works great! Thanks, and sorry about asking here as well.
https://gamedev.stackexchange.com/questions/15070/orienting-a-model-to-face-a-target