Спавнер следует за объектом, который двигается по горизонтали
У меня есть объект Evil, он двигается по горизонтали туда и обратно, а есть спавнер объектов RandomSpawner, в данный момент, Evil работает отлично, но спавнер сделан так, что он спавнит объекты Рандомно и скидывает их по вертикали, мне нужно сделать такой код, чтобы спавнер всегда следовал за объектом Virus, да и еще "выбрасывал" спрайты, так же сверху вниз!
Код Скрипта RandomSpawner:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomSpawn : MonoBehaviour
{
[SerializeField]
private GameObject obj;
float RandX;
Vector2 whereToSpawn;
[SerializeField]
private float spawnRate = 2f;
float nextSpawn = 0.0f;
[SerializeField] float distance;
[SerializeField] float speedMove;
void Start()
{
}
void Update()
{
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate;
RandX = Random.Range(-7.52f, 7.52f);
whereToSpawn = new Vector2(RandX, transform.position.y);
Instantiate(obj, whereToSpawn, Quaternion.identity);
}
}
}
Код Скрипта Evil:
using UnityEngine;
using System.Collections;
public class Evil : MonoBehaviour
{
[SerializeField] float distance;
[SerializeField] float speedMove;
void Start() => StartCoroutine(c_Start());
IEnumerator c_Start()
{
yield return new WaitForSeconds(0.2f);
Vector3 startPosition = transform.position;
Vector3 velocity = Vector3.right * speedMove;
while (true)
{
if (transform.position.x > startPosition.x + distance)
velocity.x = -speedMove;
else if (transform.position.x < startPosition.x - distance)
velocity.x = speedMove;
transform.position += velocity * Time.deltaTime;
yield return null;
}
}
}