Hello ,
I have created a player that runs forever until it hits any obstacle. The game has some buildings,cars .,etc. Now I want to spawn some Obstacles dynamically before the player.
To do this I have created an Empty GameObject called PlayerFollower and added it as a Child to the Player GameObject. So when ever the player moves forward the PlayerFollower also moves.
The script I have attached to the Player is :
using UnityEngine;
using System.Collections;
public class playerFollower : MonoBehaviour {
public Transform Player;
private GameObject Obstacle;
public GameObject Hurdles;
private Transform rotation;
// Use this for initialization
void Start () {
InvokeRepeating("createHurdles", 2, 7.0F);
}
void createHurdles()
{
Vector3 playerPos = Player.position;
Vector3 ObstaclePosition = transform.position;
ObstaclePosition.y = 1;
Obstacle = Instantiate(Resources.Load("Obstacles/Hurdle"),ObstaclePosition,transform.rotation) as GameObject;
Obstacle.transform.rotation = Player.transform.rotation;
Debug.Log("rotation :"+Obstacle.transform.rotation);
Obstacle.transform.parent = Hurdles.transform;
Debug.Log("Hurdle created at :"+ObstaclePosition);
}
// Update is called once per frame
void Update () {
float dist = Vector3.Distance(Player.position,transform.position);
Debug.Log("Distance :"+dist);
}
}
Also I want to destroy the Obstacle after the player has crossed it. I want to do this in the Update function above :
If(dist <= 3.0f)
Destroy(ObstacleObject)
But this is not an effective solution , because the distance is sometimes not less than 3.0f and if I give something like >5.0f , The Obstacle destroys in advance, before the player . Is there any better solution.
Also there are buildings , in behind , If i move the PlayerFollower also moves and it is creating Obstacles inside the buildings , how to overcome this ?
But this is an infinite runner, all of the obstacles can't be instantiated at the start because you don't know how many you will need or what direction the player will go
– thaiscorpionSure they can, you just disable the ones you've been past, reposition them in front of you and enable them again. The size of the pool will depend on how many different obstacle types there are, and how many obstacles you can see on screen at any one time.
– HannonOh yes your right, but that still doesn't solve his issue :D
– thaiscorpionYou're right it doesn't, thought I'd share a different approach though. To destroy obstacles behind the player you could place a collider (trigger) object behind the player and child it to the players transform. When OnTriggerEnter is called between the trigger object and the obstacle, disable/destroy the obstacle. You could use a similar approach to prevent your obstacles spawning inside buildings. Have trigger colliders around your buildings. If your player is inside a buildings trigger, prevent the obstacles from being placed until the player has left the trigger. Hope that helps!
– Hannon