如何统一暂停 Rigidbody2D?

How to pause a Ridigbody2D in unity?

我想知道如何暂停和恢复 rigidbody2D。我尝试了多种不同的方法,none 都奏效了。我认为主要问题是当游戏暂停时,我的 rigidbody2D 会移动,所以我需要能够暂停 rigidbody2D,并且当取消暂停时 rigidbody2D 应该像以前一样继续移动。

这是我目前的代码:

using UnityEngine;
using System.Collections;

public class Pause : MonoBehaviour {


    private Rigidbody _rigidBody;
    void Awake () 
    {
        _rigidBody = Ball.GetComponent<Rigidbody>();
    }

    private Vector3 _pausedVelocity;
    private Vector3 _pausedAngularVelocity;

    public void OnMouseEnter() 
    {
        Debug.Log("Pause with velocity=" + _rigidBody.velocity + " & angularVelocity=" + _rigidBody.angularVelocity);
        _pausedVelocity = _rigidBody.velocity;
        _pausedAngularVelocity = _rigidBody.angularVelocity;
        _rigidBody.isKinematic = true;
    }

    public void OnMouseExit() 
    {
        _rigidBody.isKinematic = false;
        _rigidBody.velocity = _pausedVelocity;
        _rigidBody.angularVelocity = _pausedAngularVelocity;
        Debug.Log("Resume with velocity=" + _rigidBody.velocity + " & angularVelocity=" + _rigidBody.angularVelocity);
    }
}

基本上这段代码附加到一个带有 collision2D 组件的空对象上,当鼠标悬停在它上面时,它会打印暂停,当鼠标移开时,它会打印播放。为了一切正常,我只需要弄清楚如何暂停 rigidbody2D!

提前致谢!

如果你想暂停所有游戏对象你可以将Time.timeScale设置为0

如果您只想暂停一个游戏对象,在暂停时存储速度和angular速度并将Rigidbody.isKinematic设置为真,在恢复时恢复原始值。

public class PausableRigidbody : MonoBehaviour {

    private Rigidbody _rigidBody;
    void Awake () 
    {
        _rigidBody = this.GetComponent<Rigidbody>();
    }

    private Vector3 _pausedVelocity;
    private Vector3 _pausedAngularVelocity;

    public void Pause() 
    {
        Debug.Log("Pause with velocity=" + _rigidBody.velocity + " & angularVelocity=" + _rigidBody.angularVelocity);
        _pausedVelocity = _rigidBody.velocity;
        _pausedAngularVelocity = _rigidBody.angularVelocity;
        _rigidBody.isKinematic = true;
    }

    public void Resume() 
    {
        _rigidBody.isKinematic = false;
        _rigidBody.velocity = _pausedVelocity;
        _rigidBody.angularVelocity = _pausedAngularVelocity;
        Debug.Log("Resume with velocity=" + _rigidBody.velocity + " & angularVelocity=" + _rigidBody.angularVelocity);
    }
}

更新 1

PausableRigidbody 实例可以通过 SerializeField 上的引用来调用,可以通过在 Unity Inspector 中选择 PausingView 并使用脚本拖动 Ball PausableRigidbody 到 Inspector 中,这样它看起来像这样:

public class PausingView : MonoBehaviour {

    [SerializeField]
    private PausableRigidbody _pausableRigidbody;

    public void OnMouseEnter() 
    {
        _pausableRigidbody.Pause();
    }

    public void OnMouseExit() 
    {
        _pausableRigidbody.Resume();
    }
}