Hey there,
Lets say im tossing a hand grenade. So it would have a curved projectile and when it hits the ground its going to explode. This is how I shoot it:
void Update () {
if (Input.GetButton("Fire1"))
{
GameObject bomb= Instantiate(projectile, transform.position, transform.rotation);
}
}
And this is the script for bomb:
void Update () {
if (transform.position.y > 0)
{
transform.Translate(Vector3.forward * Time.deltaTime * 10);
}
else
{
Destroy(this); //explode here
}
}
The problem is the bombs goes straight forward right now.
How do make sure bomb goes in a curved path?
You should add a Rigidbody component to the grenade prefab, and use the following code in the grenade script:
void OnCollisionEnter(Collision collision)
{
Destroy(this.gameObject);
}
And use the following code in the grenade launcher script:
void Update ()
{
if (Input.GetButton("Fire1"))
{
GameObject bomb = (GameObject) Instantiate(projectile, transform.position, transform.rotation);
bomb.GetComponent<Rigidbody>().AddForce(Vector3.forward * 200);
}
}
Rigidbody is a physics component which makes your gameobject behave like any normal objects - physics can affect them, which means they are aware of collision, gravity, and other forces. The first code will make sure that whenever the grenade collides with something, it will destroy itself (later on the explosion effect can be also written there, but be aware of the Destroy() function - if you implement the explosion effect with a Particle System attached to the grenade object, it will get destroyed on impact as well).
The shooter script gets the rigidbody component of the grenade, and applies force to it. Notice that you have to use bigger values than before.