c# - 如何停止 Unity 游戏对象的移动和/或旋转

标签 c# unity-game-engine

我正在制作一个基于 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/

相关文章:

c# - 在 Windows 8 CP 中设置所选 ListViewItem 的样式

c# - 将 PLC Siemens S7-1500 连接到 SQL Server 数据库

c# - 为什么要使用 getter 和 setter 方法来设置类属性?

visual-studio - 在Unity3D中单击角色时创建弹出菜单Sims的样式

c# - 游戏结束场景不起作用 (Unity C#)

Php 重定向到文件

user-interface - UI 未显示在 Unity 4.6 的 #Screen 选项卡中

c# - 如何配置 StructureMap 以使用通用存储库?

unity-game-engine - iOS 上的 AssetBundles : Memory always increases, 导致崩溃

javascript - 如何将 xml 传递给 C# 中的 View ?