I'm toying with a very simple "AI" of sorts for a 360° space RTS. The language is python, the API is Panda3D. To face a target in 3D, the AI unit just may use angular acceleration on itself (just like a player would). In each frame, I update the units orientation like this (self.rotVec is a 3-vector containing the angular velocity of the unit, combining the current axis of rotation in the vector direction with the rotation speed in the vector length):
# apply rotation to our direction
q = self.node.getQuat()
rot = self.rotVec * dt
qq = Quat(0, rot.getX(), rot.getY(), rot.getZ())
q += (qq * q) * 0.5
self.node.setQuat(q)
The update of the angular velocity according to the current target basically works like this (excerpt):
p = self.node.getPos() # position
q = self.node.getQuat() # current orientation
v = q.getForward(); v.normalize() # view
pd = self.dest - p; pd.normalize() # vector to target
# get angle to target, and axis we need to rotate around to face it
vdotpd = clamp(v.dot(pd), -1, 1) # v dot pd, clamped to -1 .. 1 range
theta = math.acos(vdotpd)
if theta > math.pi: theta = math.pi - theta
axis = v.cross(pd); axis.normalize()
thisQ = Quat(); thisQ.setFromAxisAngleRad(theta > 0 and self.rotAccel or -self.rotAccel, axis); thisQ.normalize()
# damp the current rotation to allow settling
damping = 0.99
self.unit.rotVec *= damping
rVl = self.unit.rotVec.length()
normalizedRotVec = self.unit.rotVec; normalizedRotVec.normalize()
# get current rotation (angular vel.) and convert to quaternion
currentQ = Quat()
if normalizedRotVec.length() >= .999 and normalizedRotVec.length() <= 1.001:
currentQ.setFromAxisAngleRad(rVl * dt, normalizedRotVec)
currentQ.normalize()
# combine current and needed rotation
newQ = currentQ * thisQ
# update angular speed
self.unit.rotVec = newQ.getAxisNormalized() * newQ.getAngleRad()
# clamp rot speed
if rVl > self.unit.maxRotSpeed:
self.unit.rotVec *= (1.0 / rVl * self.unit.maxRotSpeed * .99)
rVl = self.unit.rotVec.length()
Okay. Now my question/problem: The above works most of the time, but sometimes, my unit turns to face exactly 180 degrees away from the target! Sometimes, it approaches the direction to the target, almost gets there, and then suddenly turns away from it again and settles to the opposite side. And, in some rare cases, it starts to tumble and never finds the correct direction at all
So, how can I prevent this I don't really get why this happens, as I get the axis and angle needed to turn the target. Does someone see a fundamental error here, or do I need to take a different approach? I already tried to use signed angles, not inverting the rotation angle based on the angle-to-target, etc., but I get the same behaviour. So - how would you make a unit slowly turn to face a target, by just using angular acc/vel (e.g. to feed into a physics engine)?
Thanks, Cheers!