unity3d 每隔2秒移动一次对象到随机坐标

0g0grzrc  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(114)

我想让enemy每2秒移动到-2.4到2.4之间的一个随机X位置,但是他移动得很急,而且移动的距离很小。我怀疑问题出在speed * Time.deltaTime上,但是我不知道如何修复它

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random=UnityEngine.Random;

public class EnemyController : MonoBehaviour
{
    public Transform enemy;
    private float random;
    [SerializeField] private float speed = 10f;

    void Start()
    {
        StartCoroutine(MoveEnemy());
    }

    IEnumerator MoveEnemy()
    {
        while (!MainGame.lose)
        {
            yield return new WaitForSeconds(2);

            random = Random.Range(-2.4f, 2.4f);
            Debug.Log(random);
            enemy.transform.position = Vector2.MoveTowards(enemy.position,
                new Vector3(random, enemy.position.y),
                speed * Time.deltaTime);
        }
    }
}
lmvvr0a8

lmvvr0a81#

你每两秒才移动一次敌人。对我来说,听起来你更想不断地移动敌人,但每两秒才选择一个新的目标位置,所以eidogg。

// you can directly make Start a Coroutine by changing its return type 
IEnumerator Start()
{
    while (!MainGame.lose)
    {
        var random = Random.Range(-2.4f, 2.4f);
        var targetPosition = new Vector3(random, enemy.position.y);

        for(var time = 0f; time < 2f; time += Time.deltaTime)
        {
            // need to check within here since otherwise it would always try to finish the for loop
            if(MainGame.lose) 
            {
                // quits from this entire routine
                yield break;
            }

            enemy.position = Vector2.MoveTowards(enemy.position, targetPosition, speed * Time.deltaTime);

            // this basically means continue in the next frame
            yield return null;

            if(enemy.position == targetPosition) 
            {
                // quits the for loop and basically starts again from var random = ...
                break;
            }
        }
    }
}

因此,在最多两秒内,你尝试以恒定的线性运动到达这个随机目标,如果你超过2秒或在此之前到达目标,你将选择一个新的随机目标位置

相关问题