I’m following a tutorial that might be outdated at Noobtuts, so I’m not sure if the mistake is on my end or the site’s, but here’s my code for the rocket launcher. I get an explosion but no rocket comes out. I disabled collision on the weapon so the missile isn’t exploding upon contact with the gun but maybe it still is? I don’t know.
Any help would be greatly appreciated! I tried banging my head against the problem but I can’t seem to solve it on my own.
The code for the rocket.
public class Rocket : MonoBehaviour
{
// The fly speed (used by the weapon later)
public float speed = 2000.0f;
// explosion prefab (particles)
public GameObject explosionPrefab;
// find out when it hit something
void OnCollisionEnter(Collision c)
{
// show an explosion
// - transform.position because it should be
// where the rocket is
// - Quaternion.identity because it should
// have the default rotation
Instantiate(explosionPrefab,
transform.position,
Quaternion.identity);
// destroy the rocket
// note:
// Destroy(this) would just destroy the rocket
// script attached to it
// Destroy(gameObject) destroys the whole thing
Destroy(gameObject);
}
}
The code for the weapon
public class Shoot : MonoBehaviour {
// Rocket Prefab
public GameObject rocketPrefab;
// Update is called once per frame
void Update()
{
// Left mouse clicked?
if (Input.GetMouseButton(0))
{
// spawn rocket
// - Instantiate means 'throw the prefab into the game world'
// - (GameObject) cast is required because unity is stupid
// - transform.position because we want to instantiate it exactly
// where the weapon is
// - transform.parent.rotation because the rocket should face the
// same direction that the player faces (which is the weapon's
// parent.
// we can't just use the weapon's rotation because the weapon is
// always rotated like 45° which would make the bullet fly really
// weird
GameObject g = (GameObject)Instantiate(rocketPrefab,
transform.position,
transform.parent.rotation);
// make the rocket fly forward by simply calling the rigidbody's
// AddForce method
// (requires the rocket to have a rigidbody attached to it)
float force = g.GetComponent<Rocket>().speed;
g.GetComponent<Rigidbody>().AddForce(g.transform.forward * force);
}
}
}