I have created a test script that spawns an enemy object near a set target and then follows it the normal way in the screen space. So it doesn't stay on the map obviously. Since I cant figure out how to modify it to use OnlineMapsControlBase.GetScreenPosition. I'm new to programming haha
So maybe you can show how to change it so it would work as intended with the 2d map?
The scrips works this way currently:
Add the SpawnEnemy script to an empty game object, set the target and pick an enemy prefab. On start it will spawn the enemy in a random location within a radius from the target, and gives it the FollowTarget script. It will then start moving towards the target.
SpawnEnemy script added to an empty GameObject
using UnityEngine;
public class SpawnEnemy : MonoBehaviour
{
public Transform target; // target to follow
public GameObject enemyPrefab; // enemy that will spawn
public float speed = 1f; // follow speed
public float MinSpawnDistance = 10f; // Min spawn distance
public float MaxSpawnDistance = 20f; // Max spawn distance
void Start()
{
// calculate a random spawn position within the specified distance of the target
Vector2 spawnPos = Random.insideUnitCircle * Random.Range(MinSpawnDistance, MaxSpawnDistance);
spawnPos += (Vector2)target.position;
// instantiate a new enemy at the calculated spawn position
GameObject enemy = Instantiate(enemyPrefab, spawnPos, Quaternion.identity);
// attach the FollowTarget script to the new enemy and set the target to the existing target object
FollowTarget followScript = enemy.AddComponent<FollowTarget>();
followScript.target = target;
followScript.speed = speed;
}
void Update()
{
}
}
FollowTarget script that gets added to the spawned enemy:
using UnityEngine;
public class FollowTarget : MonoBehaviour
{
public Transform target; // target to follow
public float speed = 1f; // follow speed
void Start()
{
}
void Update()
{
// calculate the distance to the target
float distance = Vector2.Distance(transform.position, target.position);
// move towards the target at the specified speed
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
}