我有一个游戏对象,当玩家选择力量和方向时,使用physics.simulate绘制移动轨迹和结束位置的直线。如果我每隔0.5f秒使用它,它工作得很好,但我必须预测每一帧的轨迹和结束位置,但然后游戏就会滞后。如何预测每一帧的轨迹和结束位置?
private IEnumerator destcor()
{
while (true)
{
yield return new WaitForSeconds(0.3f);
touchhandler.listofcoll.Clear();
touchhandler.force = (float)Math.Pow(distanceToRoller, 3);
touchhandler.RollerMove();
endpos = touchhandler.CheckPosition(rollerobj.GetComponent<Rigidbody>());
destination.transform.position = endpos;
}
}
public Vector3 CheckPosition(Rigidbody defaultRb)
{
Physics.autoSimulation = false;
defaultRb = GetComponent<Rigidbody>();
Vector3 defaultPos = defaultRb.position;
Quaternion defaultRot = defaultRb.rotation;
float timeInSec = timeCheck;
while (timeInSec >= Time.fixedDeltaTime)
{
timeInSec -= Time.fixedDeltaTime;
Physics.Simulate(Time.fixedDeltaTime);
}//end while
Vector3 futurePos = defaultRb.position;
Physics.autoSimulation = true;
defaultRb.velocity = Vector3.zero;
defaultRb.angularVelocity = Vector3.zero;
defaultRb.transform.position = defaultPos;
defaultRb.transform.rotation = defaultRot;
return futurePos;
}发布于 2019-07-17 20:42:19
通常,您应该在FixedUpdate中执行与Physics引擎(也包括RigidBody)相关的所有操作,或者因为您使用的是IEnumerator,所以在每个帧的基础上使用yield return new WaitForFixedUpdate(); -而不是。
物理更新不是以帧为基础,而是以固定的时间间隔(因此称为“FixedUpdate”)进行的,这有一个很好的理由:它通常有点耗时和资源密集型。因此,为了避免巨大的延迟,你应该避免每一帧都使用物理。
另一件拖慢你速度的事情是重复进行GetComponent调用。您应该只创建一次,并在以后重用该引用:
private RigidBody rigidBody;
private void Awake()
{
rigidBody = rollerobj.GetComponent<Rigidbody>();
}
private IEnumerator destcor()
{
while (true)
{
yield return new WaitForFixedUpate();
touchhandler.listofcoll.Clear();
touchhandler.force = (float)Math.Pow(distanceToRoller, 3);
touchhandler.RollerMove();
endpos = touchhandler.CheckPosition(rigidBody);
destination.transform.position = endpos;
}
}在CheckPosition中,这一行
defaultRb = GetComponent<Rigidbody>();这没有任何意义!您要么已经传入了有效的RigidBody引用,要么没有传入。因此,在这里覆盖它似乎有点适得其反。
如果您想在这里再次使用一种后备,则宁愿将引用一次存储在Awake中,然后像这样重用它。
private RigidBody rigidBody;
private void Awake()
{
rigidBody = rollerobj.GetComponent<Rigidbody>();
// now add the fallback here already
if(!rigidBody) rigidBody = GetComponent<RigidBody>();
// or maybe you could even use
//if(!rigidBody) rigidBody = GetComponentInChildren<RigidBody>(true);
// in order to buble down the entire hierachy until a RigidBody is found
}https://stackoverflow.com/questions/57075728
复制相似问题