Question by
armandas2005 · May 26, 2021 at 11:38 AM ·
not workingmoving
Enemy stops Moving
I wrote a script where the opponent should just drive forward and change the position on the X and Y axes from time to time. But if I press x to change the axes now, my opponents just stop and the function Move() no longer works
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Transform player;
public float speed;
public float xMinBoundary;
public float xMaxBoundary;
public float zFloat;
public float randomNumber;
public float randX;
public float totalMovementTime = 2f;
public float currentMovementTime = 2f;
public bool ChangingPos;
public bool changingTrue;
private Vector3 target;
private IEnumerator MoveEnemy()
{
randomNumber = Random.Range(5, 30);
randX = Random.Range(xMinBoundary, xMaxBoundary);
target = new Vector3(randX, 0, zFloat);
while (Vector3.Distance(transform.localPosition, target) > 0)
{
ChangingPos = true;
currentMovementTime += Time.deltaTime;
transform.localPosition = Vector3.Lerp(player.position, target, currentMovementTime / totalMovementTime);
ChangingPos = false;
yield return null;
}
}
void Update()
{
zFloat = transform.position.z;
if (!ChangingPos)
{
Move();
}
if (Input.GetKeyDown(KeyCode.X))
{
StartCoroutine(MoveEnemy());
}
}
void Move()
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
Debug.Log("Moved");
}
}
Comment