面对方向的随机敌人移动

我正在尝试让我的敌舰模拟实际的宇宙飞船。因此,船只向前加速,但随着时间的推移,会朝着不同的方向移动,如所附图片所示。这需要是一个随机的面对方向,但它必须平滑地过渡到下一个方向,以停止我当前方法所产生的抖动效果。


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();

    }


尚方宝剑之说
浏览 97回答 1
1回答

隔江千里

目前你在每一帧-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));    }}
打开App,查看更多内容
随时随地看视频慕课网APP