根据标记将特定对象的重力引入

时间:2015-05-21 07:32:06

标签: c# unity3d tags gravity

我有问题。我根据重力做了很多游戏。现在我希望玩家对象对具有特定标记的其他对象具有引力。这是一场2D游戏。我怎样才能给玩家带来这种引力?我更喜欢c#脚本,但java也没关系。

感谢您的帮助!

1 个答案:

答案 0 :(得分:-1)

使用FixedUpdate方法创建脚本,并在此方法中计算并应用刚体力。

使用Newton's Law of Universal Gravitation计算脚本中的重力强度。在脚本的循环中,计算每个单独的重力向量,然后将其求和到最终的重力向量,这是游戏对象被拉向的方向。

例如(C#):

// Attach this script to gameObject that will be affected by gravity
// Ensure gameObject has rigidbody component attached and "Use Gravity" is UNCHECKED
public class GravityScript : MonoBehaviour
{

    Rigidbody rigidbody;
    Transform[] gravitySources; // Assign each Transform in inspector, these will be sources of gravity.

    void Start ()
    {
        rigidbody = GetComponent<Rigidbody>();
    }

    // NOTE: Include proper individual gravitational forces (gravity from far away objects is weaker than gravity from closer objects)
    private Vector3 CalculateGravity()
    {
        Vector3 gravity = Vector3.zero;

        // For each source of gravity accumulate total gravitational force
        foreach (Transform source in gravitySources)
        {
            // Direction of gravity
            Vector3 direction = transform.position - source.position;
            // Calculate strength of gravity at distance
            float gravitationalStrength = Vector3.Distance(transform.position, source.position) * ????;
            gravity += direction.normalized * gravitationalStrength;
        }

        return gravity;
    }

    void FixedUpdate ()
    {
        Vector3 gravity = CalculateGravity();
        rigidbody.AddForce(gravity, Forcemode.Acceleration);
    }
}