简体   繁体   English

我想在 unity3d c# 中按下一个键来冻结一个对象

[英]I want to freeze an object on pressing a key in unity3d c#

So what I want to do is when a player presses a key the object somehow deletes the rigidbody or just freezes it.所以我想要做的是当玩家按下一个键时,对象以某种方式删除刚体或只是冻结它。 I looked at the docs but I didn't understand what to look for.我查看了文档,但不明白要查找什么。

if (Input.GetKeyDown(KeyCode.F))
{

}

Also I want the player to be able to unfreeze it after he froze it.此外,我希望玩家能够在冻结后解冻。 (or recover the rigidbody when it was deleted) (或在刚体被删除时恢复刚体)

As said what you want is do freeze the Rigidbody like eg如前所述,您想要的是像例如一样冻结刚体

private Rigidbody _rigidbody;
private float velocity;

private void Awake ()
{
    _rigidbody = GetComponemt<Rigidbody>();
}

private bool isFrozen;

private void Update()
{
    if (Input.GetKeyDown(KeyCode.F))
    {
        isFrozen = !isFrozen;
        if(isFrozen) velocity = _rigidbody.velocity;
        _rigidbody.velocity = isFrozen ? Vector3.zero : velocity;
        _rigidbody.isKinematic = isFrozen;
    }
}

and when you want it to react to physics again disable isKinematic and assign back the velocity .当您希望它再次对物理做出反应时,请禁用isKinematic并重新分配velocity

You should be able to simply set 'enabled' to false on the Rigidbody component.您应该能够在 Rigidbody 组件上简单地将 'enabled' 设置为 false。

Something like this, note that it would likely make sense to cache the rigidbody on Awake() or whatever fits your context.像这样的事情,请注意,在 Awake() 或任何适合您的上下文的情况下缓存刚体可能是有意义的。

if (Input.GetKeyDown(KeyCode.F))
{
    gameObject.GetComponent<Rigidbody>().enabled = false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM