How to rotate NavMesh Agent to the surface it is walking on
Hello . I am trying to get my NPC to follow the shape of the surface he is walking on as it travels towards its target (for example: lean forward when it goes down the hill. I do raycasting to read normals of the surface, but when I try to implement that data in he will not rotate on Y axis anymore ( NPC not looking on its target anymore). It will respond to the curvature of the surface but won't rotate as he turns. So I know how to do both separately but I can't manage to get it to work together. It is a mobile game so it has to be very simple. Any help with the code would be deeply appreciated, even if someone knows a simple asset that I could purchase to solve that problem! Thanks a lot. Here is the code for grabbing surface normals:
`
downward = transform.TransformDirection(Vector3.down) * 1;
Debug.DrawRay(transform.position, downward, Color.green);
if (Physics.Raycast(transform.position,(downward), out hit, 1, mask))
{
distance = hit.distance;
sheepBody.transform.position = hit.point;
sheepBody.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);`
The way I understand it, what I need to do is to alter X and Z-axis for a navmesh but not the Y. If you know of a better way I am open. Cheerio!!
Answer by Hoorza · Nov 30, 2018 at 05:13 PM
I got it! For those looking for a solution to this problem. NaveMesh agent is placed on the parent object. Next, create child object that contains meshes and the script with the code below. And VOILA! So far my object has no animations and it works just fine, also I do not have very steep terrain in my game, so can't tell if it works well with the steeper surface. Cheerio!!
using UnityEngine;
public class SheepTerrainAlign : MonoBehaviour
{
RaycastHit hit;
Vector3 theRay;
public LayerMask terainMask;
void FixedUpdate()
{
Align();
}
private void Align()
{
theRay = -transform.up;
if (Physics.Raycast(new Vector3(transform.position.x, transform.position.y, transform.position.z),
theRay, out hit, 20, terainMask))
{
Quaternion targetRotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.parent.rotation;
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime / 0.15f);
}
}
}
Answer by Elizeuvix · Nov 07, 2021 at 12:28 PM
How to rotate object in NavmeshAgent but using WASD keys?
Your answer
Follow this Question
Related Questions
NavMesh pathing not working 0 Answers
Using HeightMesh for navigation 0 Answers
Is there a way to have a NavMeshAgent ignore inclines? 1 Answer