I'm building a game where the earth is hit by a meteorite. I have programmed the meteorite hitting the earth and both shapes have a sphere collider. I have also designed the explosion particles.
However, I don't know how to activate the explosion once the meteorite collides into the earth.
Here's my code:
Earth rotation script
using System.Collections.Generic;
using UnityEngine;
public class orbit : MonoBehaviour
{
public Transform world;
public float rotationSpeed=1f;
// Start is called before the first frame update
void Start()
{
world = GetComponent<Transform>();
Debug.Log("this works on the first frame");
}
// Update is called once per frame
void Update()
{
//code for rotating the earth
world.Rotate(new Vector3(0, rotationSpeed, 0), Space.World);
}
}
CodePudding user response:
In order to do that, you have to add Rigid Body on both elements (earth and meteorite) and activate the "Trigger" option, only on one of them. (Earth for example).
Add a new function in this script you added (the snippet of earth rotation).
Add a new variable (the prefab with your particles).
Activate "Play on Awake" on your Particle System and the "Stop action" to Destroy.
public GameObject explosionPrefab;
void OnCollisionEnter(Collision collision)
{
ContactPoint contact = collision.contacts[0];
Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
Vector3 pos = contact.point;
GameObject explosionParticle = Instantiate(explosionPrefab, pos, rot);
}