1

我想知道如何暂停一个刚体2D 并恢复它。我尝试了许多不同的方法,但都没有奏效。我认为主要问题是当游戏暂停时,我的刚体 2D 会移动,所以我需要能够暂停刚体 2D,当未暂停时,刚体 2D 应该像以前一样继续移动。

这是我到目前为止的代码:

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);
    }
}

基本上,这段代码附加到一个带有碰撞 2D 组件的空白处,当鼠标悬停在它上面时,它会打印暂停,当鼠标移开时,它会打印播放。所以一切正常,我只需要弄清楚如何暂停rigidbody2D!

提前致谢!

4

1 回答 1

3

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

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

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

可以通过SerializeFieldPausableRigidbody上的引用调用实例,可以通过在 Unity Inspector 中选择 a 并将带有脚本的 Ball 拖入 Inspector 来填充该实例,使其看起来像这样:PausingViewPausableRigidbody

具有序列化字段 PausableRigidbody 的 Unity 编辑器 PausingView

public class PausingView : MonoBehaviour {

    [SerializeField]
    private PausableRigidbody _pausableRigidbody;

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

    public void OnMouseExit() 
    {
        _pausableRigidbody.Resume();
    }
}
于 2015-09-01T06:47:03.963 回答