Home > Software design >  nav mesh agent changing the position of my gameobject
nav mesh agent changing the position of my gameobject

Time:12-12

I am spawning my animals after the game runs. When ı add nav mesh agent to my animal prefab it turns out the old position.

Here is my Code:

public class GeneralScript : MonoBehaviour
{
public GameObject Deer;
private int deernum1 = 0
private int num;



private bool cond1 = true;
private bool cond2 = true;


void Start()
{
    StartCoroutine(spawnanimalsatposition1());
    
    

}

IEnumerator spawnanimalsatposition1()
{
    yield return new WaitForSeconds(3f);
    while (cond1)
    {
        Vector3 position1 = new Vector3(Random.Range(300,495), 1, Random.Range(5, 495));
        position1.y = Terrain.activeTerrain.SampleHeight(position1)   
        Terrain.activeTerrain.GetPosition().y;                                                                
        position1.y  = 1.2f;
        Instantiate(Deer, position1, Quaternion.Euler(-90, 0, 0));
        
        deernum1  ;
        if (deernum1 > 6)
        {
            cond1 = false;
        }

    }
}

Example of my Issue: Normal Broken

Does anyone know why is this happening and how to fix it.

CodePudding user response:

In your "normal" scenario, you are using the Z-axis instead of the preferred Y-axis as the up rotation of your object.

When you're instantiating your prefab, you also apply a Euler angle offset of (-90,0,0). Which is off-setting your Transform by -90 degrees on the x-axis.

To fix this, you could either set the Euler angles to (0,0,0), or better yet use Quaternion.identity making the object align with the world axes. I'm assuming the NavMesh is attempting to normalise this offset, so ideally you should rotate your animal so that z-axis (blue) is "forward" or the face, and y-axis (green) is up

  • Related