我想知道如何暂停刚体2D并恢复它。我尝试了许多不同的方法,但都没有。我认为主要的问题是,当游戏暂停时,我的rigidbody2D将会移动,所以我需要能够暂停刚体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);
}
}
基本上这个代码附加到一个带有collision2D组件的空,当鼠标悬停在它上面时,它会打印暂停,当鼠标移开时,它会打印播放。所以一切正常,我只需要弄清楚如何暂停刚体2D!
提前致谢!
答案 0 :(得分:2)
如果你想暂停所有游戏对象你可以将Time.timeScale设置为0
如果你想暂停一个游戏对象,请暂停存储速度和角速度并将Rigidbody.isKinematic设置为true,然后在Resume上恢复原始值。
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
来填充,并使用脚本拖动球{{1}进入Inspector,看起来像这样:
PausableRigidbody