- Home /
Automatic Shooting Script
First off:
I'm from Germany sorry for my english
i've been written a Script to shoot a single Prefab.
But now i want an automatic Gun.
sooooo......
Can Anybody help me to make this shooting Script 'automatic' ?
Here is the Script:
var Projectile : Rigidbody;
var ProjectileSpeed : int = 10;
function Update () {
if (Input.GetButtonDown("Fire1")) {
var clone : Rigidbody;
clone = Instantiate(Projectile, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection (Vector3.forward * ProjectileSpeed);
}
}
That's an idea but i want something like a 'Firerate'
Answer by contab009 · Jul 31, 2014 at 09:41 PM
First of all you need to call GetButton instead of GetButtonDown. Afterwards, you need to check if enough time ( 1 / firerate ) has passed. The code would be similar to this :
var Projectile : Rigidbody;
var ProjectileSpeed : int = 10;
var FireRate : float = 10; // The number of bullets fired per second
var lastfired : float; // The value of Time.time at the last firing moment
function Update ()
{
if (Input.GetButton("Fire1"))
{
if (Time.time - lastfired > 1 / FireRate)
{
lastfired = Time.time;
var clone : Rigidbody;
clone = Instantiate(Projectile, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection (Vector3.forward * ProjectileSpeed);
}
}
}
Sorry if I missed anything and also sorry for any syntax errors, I use C# instead of JavaScript.
Answer by SchneeBaum · Jul 01, 2017 at 07:38 AM
first off, you can do this:
#pragma strict
var Effect : Transform;
var TheDamage = 100;
var FireRate = 0.5;
var LastFired : float;
var theBullet : Rigidbody;
var Speed = 20;
function Update () {
if (Input.GetButton("Fire1"))
{
if (Time.time - LastFired > 1 / FireRate) { LastFired = Time.time;
var clone = Instantiate(theBullet, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection(Vector3(0, 0, Speed));
Destroy (clone.gameObject, 3);
}
}
}
then, you can use
#pragma strict
var Dammage = 100;
function OnCollisionEnter (info : Collision)
{
info.transform.SendMessage("ApplyDammage", Dammage, SendMessageOptions.DontRequireReceiver);
}
to destroy the object
Answer by tdagloria · May 10, 2018 at 08:15 AM
sorry, @contab009 but i can't shoot with your script, the variable "Projectile" has not "been assigned to the script, can you help me?
PS: I use unity 5.1.0.
Hello. You need to assign the variable from the Unity editor, with the projectile asset.
Your answer
Follow this Question
Related Questions
Automatic Shooting Script 0 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
My gun won't fire. ( Javascript ) 1 Answer
Gun Muzzle Flash 2 Answers
Automatic accceleration 1 Answer