为了账号安全,请及时绑定邮箱和手机立即绑定

面对方向的随机敌人移动

面对方向的随机敌人移动

C#
尚方宝剑之说 2023-04-29 09:56:29
我正在尝试让我的敌舰模拟实际的宇宙飞船。因此,船只向前加速,但随着时间的推移,会朝着不同的方向移动,如所附图片所示。这需要是一个随机的面对方向,但它必须平滑地过渡到下一个方向,以停止我当前方法所产生的抖动效果。https://imgur.com/tBslTpI我目前正在尝试执行我展示的代码,但它会使敌人对象在每次旋转之间闪烁并且不平滑。    public float directionChangeTimer = 5f;    public float accelerateSpeed;    public void addRandomDirection()    {        float randomAngleAdd = Random.Range(-5f, 5f);        transform.Rotate(0, 0, randomAngleAdd);    }    public void Update()    {        //Add our Functions        addRandomDirection();    }
查看完整描述

1 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

目前你在每一帧-5之间旋转和5度数。

如果你想让这更顺畅,你可以使用协程,例如

public float directionChangeTimer = 5f;


public float anglesPerSecond = 1f;


public float accelerateSpeed;


private void Start()

{

    StartCoroutine(RandomRotations);

}


private void IEnumerator RandomRotations()

{

    while(true)

    {

        // wait for directionChangeTimer seconds

        yield return new WaitForSeconds(directionChangeTimer);


        // get currentRotation

        var startRot = transform.rotation;


        // pick the next random angle

        var randomAngleAdd = Random.Range(-5f, 5f);


        // store already rotated angle

        var alreadyRotated = 0f;


        // over time add the rotation

        do

        {

            // prevent overshooting

            var addRotation = Mathf.Min(Mathf.Abs(randomAngleAdd) - alreadyRotated, Time.deltaTime * anglesPerSecond);


            // rotate a bit in the given direction

            transform.Rotate(0, 0, addRotation * Mathf.Sign(randomAngleAdd));


            alreadyRotated += addRotation;


            yield return null;

        }

        while(alreadyRotated < Mathf.Abs(randomAngleAdd));

    }

}


查看完整回答
反对 回复 2023-04-29
  • 1 回答
  • 0 关注
  • 68 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信