我的Unity C#函数为什么返回NaN值?

huangapple go评论63阅读模式
英文:

Why is my Unity C# function returning NaN values?

问题

我正在尝试使用以下脚本来计算物体之间的重力:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gravity : MonoBehaviour
{
    public const float gravity = 10;
    public float mass = 10f;
    public bool active = true;
    public Rigidbody rigidbody;
    public Transform transform;
    GameObject[] otherObjs;
    Gravity[] otherGravities;

    void Start () {
        rigidbody = gameObject.GetComponent<Rigidbody>();
        transform = gameObject.transform;
        otherObjs = GameObject.FindGameObjectsWithTag("Body");
        otherGravities = new Gravity[otherObjs.Length];
        for (int i = 0; i < otherObjs.Length; i++)
        {
            otherGravities[i] = otherObjs[i].GetComponent<Gravity>();
        }
    }

    void FixedUpdate () {
        rigidbody.AddForce(CalculateGravity());
    }

    Vector3 CalculateGravity () {
        Vector3 finalGravity = new Vector3(0, 0, 0);
        foreach (Gravity current in otherGravities) {
            float distance = Vector3.Distance(transform.position, current.transform.position);
            Vector3 unNormalDirection = transform.position - current.transform.position;
            Vector3 direction = unNormalDirection.normalized;
            Vector3 gravitationalPull = ((mass * current.mass) / (distance * distance)) * direction;
            finalGravity += gravitationalPull;
        }
        return finalGravity;
    }
}

在运行代码时,我得到以下错误信息:

rigidbody.force assign attempt for 'Sun' is not valid. Input force is { NaN, NaN, NaN }.
UnityEngine.Rigidbody:AddForce (UnityEngine.Vector3)
Gravity:FixedUpdate () (at Assets/Scripts/Gravity.cs:27)

我在场景中的两个对象都出现了这个错误。我似乎无法弄清楚为什么该函数返回NaN,我已经反复检查它是否未除以零。如果您有任何想法,请告诉我。

英文:

I am trying to calculate gravity between bodies using the following script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gravity : MonoBehaviour
{
    public const float gravity = 10;
    public float mass = 10f;
    public bool active = true;
    public Rigidbody rigidbody;
    public Transform transform;
    GameObject[] otherObjs;
    Gravity[] otherGravities;

    void Start () {
        rigidbody = gameObject.GetComponent&lt;Rigidbody&gt;();
        transform = gameObject.transform;
        otherObjs = GameObject.FindGameObjectsWithTag(&quot;Body&quot;);
        otherGravities = new Gravity[otherObjs.Length];
        for (int i = 0; i &lt; otherObjs.Length; i++)
        {
            otherGravities[i] = otherObjs[i].GetComponent&lt;Gravity&gt;();
        }
    }

    void FixedUpdate () {
        rigidbody.AddForce(CalculateGravity());
    }

    Vector3 CalculateGravity () {
        Vector3 finalGravity = new Vector3(0, 0, 0);
        foreach (Gravity current in otherGravities) {
            float distance = Vector3.Distance(transform.position, current.transform.position);
            Vector3 unNormalDirection = transform.position - current.transform.position;
            Vector3 direction = unNormalDirection.normalized;
            Vector3 gravitationalPull = ((mass * current.mass) / (distance * distance)) * direction;
            finalGravity += gravitationalPull;
        }
        return finalGravity;
    }
}

When running the code, I get the following error

rigidbody.force assign attempt for &#39;Sun&#39; is not valid. Input force is { NaN, NaN, NaN }.
UnityEngine.Rigidbody:AddForce (UnityEngine.Vector3)
Gravity:FixedUpdate () (at Assets/Scripts/Gravity.cs:27)

I get this for both objects in the scene.
I can't seem to figure out why the function is returning NaN's, I've double checked that it is not dividing by zero. If you have any idea, please let me know.

答案1

得分: 2

这是我基于一些假设的翻译。看起来你可能是在计算物体之间的重力吸引力,距离为0,然后除以这个0

在这一行代码中:otherObjs = GameObject.FindGameObjectsWithTag("Body"); 你正在获取所有带有标签"Body"的对象,其中可能包括你正在应用重力的对象。我建议尝试像这样筛选它们:

void Start () {
    rigidbody = gameObject.GetComponent<Rigidbody>();
    transform = gameObject.transform;
    otherObjs = GameObject.FindGameObjectsWithTag("Body");
    int otherGravitiesLength = otherObjs.Length;
    if (gameObject.CompareTag("Body")) {
        //必须将该对象从其自身的其他引力列表中排除。
        //因此不要将其包括在该数组的长度中。
        otherGravitiesLength = otherGravitiesLength - 1;
    }
    otherGravities = new Gravity[otherGravitiesLength];
    int insertIndex = 0;
    for (int i = 0; i < otherObjs.Length; i++)
    {
        if (otherObjs[i] != gameObject) {
            otherGravities[insertIndex++] = otherObjs[i].GetComponent<Gravity>();
        }
    }
}

我从上下文和少量的谷歌搜索中推测,因为我从未使用过Unity,所以这个答案可能需要进一步修正。

如果两个具有引力吸引力的不同物体可能位于相同位置,那么你可能仍然需要在CalculateGravity内进行零距离的测试,并以不同的方式处理。

英文:

I'm basing this on a few assumptions. It looks like you're probably calculating gravitational attraction to bodies from themselves, with a distance of 0, and dividing by that 0.

In the line otherObjs = GameObject.FindGameObjectsWithTag(&quot;Body&quot;); you're getting all objects with the tag &quot;Body&quot; which probably includes objects you're applying gravity to. I'd try to filter them something like this:

    void Start () {
        rigidbody = gameObject.GetComponent&lt;Rigidbody&gt;();
        transform = gameObject.transform;
        otherObjs = GameObject.FindGameObjectsWithTag(&quot;Body&quot;);
        int otherGravitiesLength = otherObjs.Length;
        if (gameObject.CompareTag(&quot;Body&quot;)) {
            //Must exclude this object from its own other gravities list.
            //So don&#39;t include it in the length of that array.
            otherGravitiesLength = otherGravitiesLength - 1;
        }
        otherGravities = new Gravity[otherGravitiesLength];
        int insertIndex = 0;
        for (int i = 0; i &lt; otherObjs.Length; i++)
        {
            if (otherObjs[i] != gameObject) {
                otherGravities[insertIndex++] = otherObjs[i].GetComponent&lt;Gravity&gt;();
            }
        }
    }

I've never used Unity, so I'm making some guesses about the API from context, and a tiny bit of googling, so this answer may need some repair.

If it is possible for two distinct bodies that gravitationally attract to be in the same position, then you should probably still also test for a zero distance and handle that differently within CalculateGravity

huangapple
  • 本文由 发表于 2023年2月6日 10:22:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定