我希望我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);
}
}
}
uj5u.com熱心網友回復:
你每兩秒只移動一次敵人。對我來說,聽起來你寧愿不斷移動敵人,但每 2 秒只選擇一個新的目標位置,例如
// 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 秒或在此之前到達目標,則選擇一個新的隨機目標位置
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530333.html
標籤:C#unity3d
