我正在制作一个基于 Unity 的滚球教程的小游戏,尽管我还没有使用过实际的教程。我加入了重生机制,但如果你在死亡时四处移动,那么在你重生后,你在着陆后仍然具有这种动力。我尝试解决这个问题,但我不知道如何解决,因为我对使用 Unity 还很陌生。我有一个视频显示了这一点:https://drive.google.com/open?id=1752bPBDVOe2emN_hmnlPaD4uaJQITpsP
这是处理重生的 C# 脚本:
public class PlayerBehavior : MonoBehaviour
{
Rigidbody PlayerRB;
public bool Dead;
private int timer;
public GameObject Particles;
public bool InRespawn;
void Update()
{
PlayerRB = GetComponent<Rigidbody>();
if (Dead)
{
StartCoroutine("Respawn");
}
}
IEnumerator Respawn()
{
InRespawn = true; //Used to prevent movement during respawn.
PlayerRB.useGravity = false;
transform.position = new Vector3(0, 4, 0);
transform.rotation = new Quaternion(-80, 0, 0, 0); // Resets position.
Dead = false;
Instantiate(Particles, transform); // Adds respawn particle effect.
yield return new WaitForSeconds(2);
Destroy(this.gameObject.transform.GetChild(0).gameObject);
PlayerRB.useGravity = true;
PlayerRB.AddForce(0, 400, 0); // Does a little hop.
InRespawn = false; // Tells the game that respawn is finished.
}
}
最佳答案
重生时将刚体速度归零:
IEnumerator Respawn()
{
PlayerRB.velocity = Vector3.zero;
// ... rest of method
}
顺便说一句,您可能不需要在每个帧上运行 GetComponent
。这是一项昂贵的操作,因此最好尽可能少做,以免发生:
void Start()
{
PlayerRB = GetComponent<Rigidbody>();
}
void Update()
{
if (Dead)
{
StartCoroutine("Respawn");
}
}
如果您想在玩家死亡时禁用与玩家的所有物理交互,您可以在该时间内将其设置为运动学。只需确保在对其施加力量之前取消设置 isKinematic
即可。
IEnumerator Respawn()
{
PlayerRB.isKinematic = true;
// ... rest of method
PlayerRB.isKinematic = false;
PlayerRB.useGravity = true;
PlayerRB.AddForce(0, 400, 0); // Does a little hop.
InRespawn = false; // Tells the game that respawn is finished.
}
关于c# - 如何停止 Unity 游戏对象的移动和/或旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58718088/