赞
踩
看一个小游戏的源码时的时候,看到有这么一句代码:
GetComponent<Rigidbody>().WakeUp ();
愣了一下,去官网查了一下API,它的意思唤醒一个沉睡的Rigidbody,难道刚体也能睡觉?对呀,因为这是为了优化。
那,原话是这么说的:When a Rigidbody is moving slower than a defined minimum linear or rotational speed, the physics engine assumes it has come to a halt. When this happens, the GameObject does not move again until it receives a collision or force, and so it is set to “sleeping” mode. This optimisation means that no processor time is spent updating the Rigidbody until the next time it is “awoken” (that is, set in motion again).
大白话翻译:当一个刚体比定义的最小线性速度或者旋转速度小时,物理引擎就会假定刚体暂时不使用,直到接受了一个碰撞或者外力,否则就进入了睡眠状态,会节约性能。
那,如果睡眠了,会发生什么?bug!!!
且看下一段原话(准确的描述了bug如何产生):For most purposes, the sleeping and waking of a Rigidbody component happens transparently. However, a GameObject might fail to wake up if a Static Collider (that is, one without a Rigidbody) is moved into it or away from it by modifying the Transformposition. This might result, say, in the Rigidbody GameObject hanging in the air when the floor has been moved out from beneath it. In cases like this, the GameObject can be woken explicitly using the WakeUp
function. See the Rigidbody and Rigidbody 2Dcomponent pages for more information about sleeping.
大白话翻译:对于一般情况(目的),睡眠和苏醒是可自由切换的(开始翻译的自己都看不懂模式///),然而,有那么一种情况,当一个拥有静态碰撞体(ps:没有刚体的碰撞体)移入或者移出带刚体的对象时,是不能够唤醒rigidbody的(省略500字)。
那,我建了一个测试的scene,包含一个Sphere(带有刚体),Cube(无刚体)
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class Test : MonoBehaviour {
-
- public Rigidbody sphere;
- // Use this for initialization
- void Start () {
-
- }
-
- // Update is called once per frame
- void Update () {
- if(Input.GetKey(KeyCode.Space))
- {
- sphere.Sleep();
- transform.Translate(Vector3.up * Time.deltaTime);
- }
- }
- }
这段代码添加到cube,然后给sphere赋值,运行,等到小球落下后(最好再缓0.5s),按下空格键,结果如图:
成功穿透。
如果想要不穿透,那就按键前进行唤醒。当然,出了自动睡眠外,还可以强制睡眠(至少睡眠一帧),调用Sleep()方法即可。也可以自定义自动达到睡眠的线速度(sleepVelocity),角速度(sleepAngularVelocity)。
完。。。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。