hi there, i am working on a bit of a short flight sim, i have my flight engine down the way i want it and working. now all i need is a simple “bomb” projectile script.
so I’m thinking on a button press, the airplane object just creates a child “bomb” object that just spawns from the plane’s current position, and since it’s a bomb, just drops to the ground and explodes once it collides with the ground. no forward forces necessary.
anyone out there that can help me figure out a quick way to create a projectile script like that, or know where i can find one?
thanks!
The following code is directly from the scripting reference. Should get you started.
// Instantiate a rigidbody then set the velocity
var projectile : Rigidbody;
function Update () {
// Ctrl was pressed, launch a projectile
if (Input.GetButtonDown("Fire1")) {
// Instantiate the projectile at the position and rotation of this transform
var clone : Rigidbody;
clone = Instantiate(projectile, transform.position, transform.rotation);
// Give the cloned object an initial velocity along the current
// object's Z axis
clone.velocity = transform.TransformDirection (Vector3.forward * 10);
}
}
This code would be attached to the plane. Then just create your bomb/projectile as a prefab and drop it onto the projectile slot in the inspector. However, dropping a bomb isn’t completely trivial. When a real bomb drops, it takes on the velocity of the airplane until it clears the bomb bay doors, then slows down due to air drag. To make it realistic might take some tweaking, including adding drag through code and delaying that drag for a second or so. In the above code, they give the projectile a forward velocity of 10. You’ll probably have to create a variable to match that velocity to the plane’s velocity.
As for the bomb exploding, just use OnCollisionEnter() to detect the hit on the ground, then use Destroy() to kill the projectile and then Instantiate() again to replace it with an explosion prefab and sound effect. Each of these functions is fairly clearly explained in scripting reference. This script would get attached to your bomb prefab. Hope this helps.
please i have an error when coding this with c# although it is written like this at the scripting manual here:
Unity/Editor/Data/Documentation/Documentation/ScriptReference/Object.Instantiate.html
here is the code at the manual:
public class example : MonoBehaviour {
public Rigidbody projectile;
void Update() {
if (Input.GetButtonDown(“Fire1”)) {
Object clone;
clone = (Rigidbody)Instantiate(projectile, transform.position, transform.rotation);
//clone;
clone.velocity = transform.TransformDirection(Vector3.forward * 10);
}
}
}
error CS1061: Type UnityEngine.Object' does not contain a definition for velocity’ and no extension method velocity' of type UnityEngine.Object’ could be found (are you missing a using directive or an assembly reference?)