I haven't been at my computer learning code or game dev in a few months and am just starting again. I am trying to make a game very similar to Asteroids. In 3d but fixed camera from above so basically disregarding the Y Axis at the moment.
I have everything working fine so far such as the rocket stays in middle and can rotate, and fire weapon. The Asteroids for now all come from the top side of the screen, and have some code to randomise the X location and speeds.
When the laser hits the Asteroid I want it to destroy that Asteroid and create two more that are half the size and with a Rotation added of 45/-45 degrees.
I have the code that I thought would work but it is only creating one more and not two. (note: as you'll see I have tried making tempAsteroid2 and even asteroidPrefab2, before this I just had the one which I tried to instantiate twice).
What am I missing? why does this code not make two more appear upon laser collision??
Any help massively appreciated as always. Many thanks:
public class Asteroid : MonoBehaviour {
float speed;
public GameObject asteroidPrefab, asteroidPrefab2;
public int sizeKey = 2;
// Use this for initialization
void Start () {
if (sizeKey < 1)
{
Destroy(this.gameObject);
}
transform.position.Set(transform.position.x, 0f, transform.position.y);
speed = Random.Range(0.5f, 2f);
}
// Update is called once per frame
void Update () {
GetComponent<Rigidbody>().transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Laser")
{
BreakAsteroidInHalf();
Destroy(other.gameObject);
}
}
void BreakAsteroidInHalf()
{
GameObject tempAsteroid = asteroidPrefab;
tempAsteroid.transform.position = transform.position;
tempAsteroid.transform.Rotate(0, -45, 0);
tempAsteroid.transform.localScale *= 0.5f;
tempAsteroid.GetComponent<Asteroid>().sizeKey -= 1;
Instantiate(tempAsteroid);
GameObject tempAsteroid2 = asteroidPrefab2;
tempAsteroid2.transform.position = transform.position;
tempAsteroid2.transform.Rotate(0, 45, 0);
tempAsteroid2.transform.localScale *= 0.5f;
tempAsteroid2.GetComponent<Asteroid>().sizeKey -= 1;
Instantiate(tempAsteroid2);
Destroy(this.gameObject);
Debug.Log("Asteroid destroyed and replaced by 2 more");
}