- Home /
A.I Movement Based on Timer
So I'm creating a game where you have to tend a campfire to prevent the enemies from moving closer and attacking you resulting in a game over. What I need to know is what kind of code would work to have the enemy teleport closer to you based on the time decreasing. I already have a timer script attached to the fire but then reset it's position if the timer gets increased.
Here is the script for the fire
using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine.UI; using UnityEngine;
public class Gameovertimer : MonoBehaviour { public float timeLeft = 30;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
timeLeft -= Time.deltaTime;
if (timeLeft <= 0.0f)
{
Debug.Log("Fire Out");
}
if (timeLeft <= -15f)
{
Debug.Log("GameOver");
SceneManager.LoadScene("GameOver");
}
}
public void ButtonPressed()
{
if (timeLeft <= 0.0f)
timeLeft = 15;
}
}
Here is the script that increases the timer
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Wood : MonoBehaviour { public Extinguish extinguish; void OnMouseDown() { Destroy(gameObject); extinguish.timeLeft += 15; } }
I'm still learning about A.I so I don't have a script for the enemy yet
I'm very new to unity so any help would be appreciated.
Answer by Llama_w_2Ls · Jan 15, 2021 at 07:42 PM
If you had an enemy script, the smaller the amount of time is left, the more frequently the enemy may teleport towards your position. For example:
void Start()
{
StartCoroutine(MoveEnemy());
}
IEnumerator MoveEnemy()
{
while (true)
{
yield return new WaitForSeconds(timeLeft);
// After some time, move the enemy towards the player
Vector3.MoveTowards(EnemyPos, PlayerPos, TeleportDistance);
}
}
The value timeLeft
might need to be a positive number, however, as you can't wait for -15 seconds before the next enemy movement. @Frobegames
One final improvement would be to only allow the enemy to move closer if the fire is out, else move away.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
How can I more optimize My AI Script 0 Answers
Formats of High Score 1 Answer
deactivate script for period of time after script is used. 0 Answers