首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Physics.Simulate每帧

Physics.Simulate每帧
EN

Stack Overflow用户
提问于 2019-07-17 20:20:51
回答 1查看 169关注 0票数 0

我有一个游戏对象,当玩家选择力量和方向时,使用physics.simulate绘制移动轨迹和结束位置的直线。如果我每隔0.5f秒使用它,它工作得很好,但我必须预测每一帧的轨迹和结束位置,但然后游戏就会滞后。如何预测每一帧的轨迹和结束位置?

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

发布于 2019-07-17 20:42:19

通常,您应该在FixedUpdate中执行与Physics引擎(也包括RigidBody)相关的所有操作,或者因为您使用的是IEnumerator,所以在每个帧的基础上使用yield return new WaitForFixedUpdate(); -而不是

物理更新不是以帧为基础,而是以固定的时间间隔(因此称为“FixedUpdate”)进行的,这有一个很好的理由:它通常有点耗时和资源密集型。因此,为了避免巨大的延迟,你应该避免每一帧都使用物理。

另一件拖慢你速度的事情是重复进行GetComponent调用。您应该只创建一次,并在以后重用该引用:

代码语言:javascript
复制
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中,这一行

代码语言:javascript
复制
defaultRb = GetComponent<Rigidbody>();

这没有任何意义!您要么已经传入了有效的RigidBody引用,要么没有传入。因此,在这里覆盖它似乎有点适得其反。

如果您想在这里再次使用一种后备,则宁愿将引用一次存储在Awake中,然后像这样重用它。

代码语言:javascript
复制
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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57075728

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档