- Home /
Correct Normal alignment while keeping heading rotation from NavMeshAgent?
Hey guys, I have a cow. This cow should only rotate on the local x-axis regarding the normal of the terrain. And it should use the y-axis from the NavMeshAgent the rotate the heading of the cow.
So far my code looks like this and it works 95% of the time. But sometimes the cow sticks its head into the terrain. Basically flipping the local x-axis value. How can I improve this code?
Setup: Parent Empty(NavMeshAgent, BehaviorCow.cs) -> Cow Mesh + LOD
using UnityEngine;
using UnityEngine.AI;
public class BehaviorCow : MonoBehaviour
{
//states 0 idle, 1 walk, 2 turn left, 3 turn right
int animatorState;
Vector3 target;
public Terrain terrain;
NavMeshAgent agent;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Mouse0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (terrain.GetComponent<Collider>().Raycast(ray, out hit, Mathf.Infinity))
{
target = hit.point;
agent.SetDestination(target);
Debug.Log(target);
}
}
rotateToNormal(target);
}
void rotateToNormal(Vector3 destination)
{
float y = transform.localRotation.eulerAngles.y;
Vector3 terrainSize = terrain.terrainData.size;
Vector3 normal = terrain.terrainData.GetInterpolatedNormal(transform.position.x / terrainSize.x, transform.position.z / terrainSize.z);
Debug.Log(normal);
transform.localRotation = Quaternion.FromToRotation(Vector3.up, normal);
transform.localRotation = Quaternion.Euler(transform.localRotation.eulerAngles.x, y, 0);
}
}
Your answer
Follow this Question
Related Questions
How to keep an Object looking in a direction when the Joystick Input is zero 1 Answer
hit.normal rotation problem, help please really confused 1 Answer
Making the avatar look toward a specific direction 2 Answers
Best way to rotate a NavMesh AI to face the player or a specific direction? 0 Answers
Bound the gameobject from the ground 1 Answer