- Home /
AI Steering in 3D
Hello all!
I'm currently working on spicing up enemy movement in a 3D environment. Previously, I've used Quaternion.RotateTowards and the like in order to turn objects towards specific directions but I've always wanted them to have little quirks like being able to oversteer and correcting themselves constantly instead of precisely dead centering on the chosen course 100% of the time.
I've gotten pretty close to the desired behavior with this:
Vector3 targetRotLoc = transform.InverseTransformDirection(targetRot);
if (targetRotLoc.y > 0.1)
xSpeed -= homingSpeed * Time.deltaTime;
else if (targetRotLoc.y < -0.1)
xSpeed += homingSpeed * Time.deltaTime;
else
{
if (xSpeed > 0)
xSpeed -= homingSpeed * Time.deltaTime;
else if (xSpeed < 0)
xSpeed += homingSpeed * Time.deltaTime;
}
if (targetRotLoc.x > 0.1)
ySpeed += homingSpeed * Time.deltaTime;
else if (targetRotLoc.x < -0.1)
ySpeed -= homingSpeed * Time.deltaTime;
else
{
if (ySpeed > 0)
ySpeed -= homingSpeed * Time.deltaTime;
else if (ySpeed < 0)
ySpeed += homingSpeed * Time.deltaTime;
}
xSpeed = Mathf.Clamp(xSpeed, -shotProfile.homingSpeed, shotProfile.homingSpeed);
ySpeed = Mathf.Clamp(ySpeed, -shotProfile.homingSpeed, shotProfile.homingSpeed);
transform.Rotate(new Vector3(xSpeed, ySpeed, 0));
And they work well for the most part until they run into certain cases.
A. when the target vector is directly above or below them in World space. They'll just keep steering away and never reach their target.
B. If the target evades them for long enough, they sometimes become incapable of pursuing and just turn in one direction forever (gimbal lock, I assume)
So I'm looking for either some way to fix the issues listed above or a way to add the desired oversteering/correction behavior to the usual Quaternion.RotateTowards method.
For clarity, here's how I used to turn them towards the targetRot before:
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(targetRot), homingSpeed * Time.deltaTime);
It works very well, but is a bit sterile for my tastes.
Any help is appreciated!
Your answer
![](https://koobas.hobune.stream/wayback/20220613034119im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rotation Complications + rotation with parents and children? 1 Answer
Rotating 2D sprite to match surface. 0 Answers
align to floor in local X 2 Answers
Some Issue With Quaternions Short Way 0 Answers
Inverse of Quaternion.eulerAngles? 0 Answers