I am so close to figuring this out. A random running player is selected from the array and placed in a random spawn location (also obtained from an array). If the player spawns on the right he faces and runs to the left side and vice versa. I have gotten my code to do this, but it is inconsistent with the player sometimes spawning in the wrong direction. What is causing this? Thanks in advance!
Here's my code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TempSpawner : MonoBehaviour{
public float runningPlayerSpeed;
public Transform []spawnPoints;
public float spawnTime = 2f;
public GameObject [] Players;
public SpriteRenderer mySpriteRenderer;
public float minSpeed;
public float maxSpeed;
private float currentSpeed;
void Awake ()
{
mySpriteRenderer = GetComponent();
}
void Start(){
InvokeRepeating ("SpawnPlayers", spawnTime, spawnTime);
currentSpeed = Random.Range (minSpeed, maxSpeed);
int spawnIndex = Random.Range (0, spawnPoints.Length);
foreach (var player in Players) {
if (spawnPoints [spawnIndex].position.x == 10) {
player.GetComponent ().flipX = true;
}
else if (spawnPoints [spawnIndex].position.x == -10) {
player.GetComponent ().flipX = false;
}
}
}
void Update(){
float amountToMove = currentSpeed * Time.deltaTime;
transform.Translate (Vector3.right * amountToMove);
int spawnIndex = Random.Range (0, spawnPoints.Length);
//int objectIndex = Random.Range (0, Players.Length);
foreach (var player in Players ){
if (spawnPoints [spawnIndex].position.x == 10) {
player.GetComponent ().flipX = true;
//SpriteRenderer sr = gameObject.GetComponent();
//sr.flipX = true;
//Players [objectIndex].GetComponent (mySpriteRenderer );
//mySpriteRenderer.flipX = true;
//Players [objectIndex].transform.localScale.x == -1f;
//mySpriteRenderer.flipX = true;
//GameObject.FindGameObjectsWithTag ("Running Players");
} else if (spawnPoints [spawnIndex].position.x == -10) {
player.GetComponent ().flipX = false;
}
}
}
void SpawnPlayers(){
int spawnIndex = Random.Range (0, spawnPoints.Length);
int objectIndex = Random.Range (0, Players.Length);
Instantiate (Players [objectIndex], spawnPoints [spawnIndex].position, spawnPoints [spawnIndex].rotation );
}
}
↧