统一重力到特定的对象取决于标签

本文关键字:对象 标签 取决于 一重 | 更新日期: 2023-09-27 17:50:17

我有一个问题。我正在制作一款非常依赖重力的游戏。现在我希望播放器对象对其他带有特定标签的对象具有重力。这是一款2d游戏。我该如何给予玩家这种吸引力?我更喜欢c#脚本,但是java也可以。

谢谢你的帮助!

统一重力到特定的对象取决于标签

创建一个带有fixeduupdate方法的脚本,并在该方法中计算和应用刚体力。

使用牛顿万有引力定律计算剧本中的重力强度。在脚本的循环中,计算每个单独的重力矢量,然后将其总结为最终的重力矢量,这是游戏物体被拉向的方向。

例如(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);
    }
}