- Home /
Make object move in a direction depending on where it spawns? (C#)
Hello! I have some enemies that I would like to "glide" over the screen using transform.translate, the only problem is that I'm not sure how to do this because I spawn out the enemies at a random spawnIndex that is placed on the map.
I'm trying to make it so that when an enemy spawn for example on the top of the screen, it will move downwards on the y-axis, and when the enemy spawns at the bottom it will move upwards on the y-axis.
Should I use a IF statement to check if the enemy spawns at a specific spawnIndex or should I use addforce on the object?
Here's the code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EnemySpawn : MonoBehaviour
{
// EnemyPrefabs
public GameObject EnemyFlyByPrefab;
//Show where spawn is prefab
public GameObject ShowEnemySpawn;
// Array of spawn points
public Transform[] spawnPointsEnemyFlyBy;
//Used to put active enemies in a list
public static List<GameObject> activeEnemies;
void Start ()
{
// Starts a coroutine function for spawning bouncing enemies and fly by enemy
StartCoroutine(SpawnEnemyFlyBy());
}
void Awake()
{
// Create the list
activeEnemies = new List<GameObject>();
}
void Update()
{
IEnumerator SpawnEnemyFlyBy()
{
//Wait 3 to 5 seconds when game starts to spawn the fly by enemy
yield return new WaitForSeconds(Random.Range(1, 1));
while(true)
{
// Find a random index between zero and one less than the number of spawn points.
int spawnPointIndex = Random.Range (0, spawnPointsEnemyFlyBy.Length);
// Show spawn location for one second
Object marker = Instantiate(ShowEnemySpawn, spawnPointsEnemyFlyBy[spawnPointIndex].position, Quaternion.identity);
yield return new WaitForSeconds(1);
Destroy(marker);
// Spawn enemy
GameObject newEnemy = (GameObject) Instantiate(EnemyFlyByPrefab,
spawnPointsEnemyFlyBy[spawnPointIndex].position,
spawnPointsEnemyFlyBy[spawnPointIndex].rotation);
// **THIS DOESN'T WORK, HOW CAN I FIX IT?**
/*if(spawnPointIndex == 1 || spawnPointIndex == 2 || spawnPointIndex == 3)
{
GameObject.Find("Enemy_fly_by").transform.Translate(0, 15, 0);
}*/
activeEnemies.Add(newEnemy);
yield return new WaitForSeconds(Random.Range(4, 6));
}
}
Answer by MobinYaqoob · Apr 20, 2016 at 09:36 AM
Use tags. For Example your upper spawn point are tag like "UpperSpawnPoint" and lower are tag like "LowerSpawnPoint"
So just before you instantiate an enemy object where you randomly get the spawn point check what its tag either its UpperSpawnPoint or LowerSpawnPoint so instantiate and on that tag basic make a if check and apply the force Easy :)
There we go, thank you my friend I got it to work! :D