- Home /
Rotate AI towards target, on single axis?
Hi, I'm a beginner and I'm using C# for scripting. My problem is that my AI who is chasing me (it's target), is doing so within all the axis's. I only want it to turn horizontally and not be able to look up or down. This because it interferes with my gravity, it makes him fall through the ground.
Relevant code:
if (Vector3.Distance(target.position, myTransform.position) < minDistance) <---- Checking if he's in range (don't worry, it's the right variables)
{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), aiRotationSpeed * Time.deltaTime); <---- Rotates towards target in all axis's.
if (Vector3.Distance(target.position, myTransform.position) > maxDistance) <---- Checking if he's too close.
{
myTransform.position += myTransform.forward * aiCombatSpeed * Time.deltaTime; <---- Move towards target.
}
}
else <---- I want him to randomly roam. This part works.
{
transform.Rotate(0, randRot * aiRotationSpeed * Time.deltaTime, 0);
myTransform.position += myTransform.forward * aiMoveSpeed * Time.deltaTime;
}
My question is: How do I make this piece of code work for just the horizontal axis's?
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), aiRotationSpeed * Time.deltaTime);
Best regards!
Answer by syclamoth · Oct 27, 2011 at 10:23 AM
Whenever you would have 'target.position' in the myTransform.rotation line, modify that value to have the same y coordinate as the AI.
Vector3 fixedTargetPosition =
new Vector3(target.position.x, transform.position.y, target.position.z);
Then, all of your calculations will disregard height.
Your answer
Follow this Question
Related Questions
How to rotate ? 2 Answers
Doesn't Add Rotation Over 180 2 Answers
Rotating a character's velocity? 3 Answers
Simulating 3D object rotation in a 2D space/system? 1 Answer
JS Enemy Angle Rotation Follow 1 Answer