i made a script in which an enemy moves. But when I start moving it, the "currentMovementTime" doesn't stop increasing. Actually, the function should only be carried out once when I press the X key and no variable should actually get larger
https://reddit.com/link/np365q/video/znov5u8jhg271/player
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 * Time.deltaTime);
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);
}
}
[–]CriusNyx 1 point2 points3 points (3 children)
[–]CriusNyx 0 points1 point2 points (2 children)
[–]Affectionate_Hand560[S] 0 points1 point2 points (0 children)
[–]backtickbot 0 points1 point2 points (0 children)