涉及球体重力的unity3d旋转问题

时间:2019-01-01 19:50:46

标签: c# unity3d game-engine game-physics

因此在3d统一中,我遇到了使用角色控制器通过我使用的3d重力系统旋转玩家游戏对象的情况。这是脚本:

using System.Collections;
using UnityEngine;

[RequireComponent (typeof (Rigidbody))]
public class GravityBody : MonoBehaviour {

    public GravityAttractor attractor;
    private Transform myTransform;

    void Start () {
        GetComponent<Rigidbody> ().useGravity = false;
        GetComponent<Rigidbody> ().constraints =
            RigidbodyConstraints.FreezeRotation;
        myTransform = transform;
    }

    void FixedUpdate () {
        if (attractor) {
            attractor.Attract (myTransform);
        }
    }

    void OnTriggerEnter (Collider col) {
        GravityAttractor obj = col.GetComponent ("GravityAttractor") as
        GravityAttractor;
        if (obj) {
            attractor = obj;
        }
    }

    void OnTriggerExit (Collider col) {
        attractor = null;
    }

}

和:

using System.Collections;
using UnityEngine;

public class GravityAttractor : MonoBehaviour {

    public float gravity = 0;
    public float rotationSmoothness = 5f;
    public float density = 5.52f;
    private float volume;

    public void Start () {
        if (gravity == 0) {
            if (GetComponent<Collider> ().GetType () == typeof (SphereCollider)) {
                volume = (GetComponent<Collider> ().bounds.size.x * Mathf.PI) / 6;
            } else if (GetComponent<Collider> ().GetType () == typeof (CapsuleCollider)) {
                volume = ((Mathf.PI * GetComponent<Collider> ().bounds.size.x * GetComponent<Collider> ().bounds.size.y) * GetComponent<Collider> ().bounds.size.z) / 4;
            } else {
                volume = GetComponent<Collider> ().bounds.size.x * GetComponent<Collider> ().bounds.size.y * GetComponent<Collider> ().bounds.size.z;
            }
            gravity = -((density / 10) * volume) / 2;
        }
    }

    public void Attract (Transform body) {
        Vector3 gravityUp = (body.position - transform.position).normalized;
        Vector3 localUp = body.up;

        body.GetComponent<Rigidbody> ().AddForce (gravityUp * gravity);

        Quaternion targetRotation = Quaternion.FromToRotation (localUp, gravityUp) * body.rotation;
        body.rotation = Quaternion.Slerp (body.rotation, targetRotation, rotationSmoothness * Time.deltaTime);
    }

}

问题是,每当我尝试添加标准的统一第三人称控制器时,角色尝试旋转as seen in this video

时就会出现问题

如果有人知道该怎么办,我将不胜感激。 (我使用的是最新的统一版本)

0 个答案:

没有答案