Tank script, wont shoot forward and "die"...

The code below is from someone else, I tried figuring it out but, I’m only a modeler. I’m a scripter learning in progress. Anyways, this makes my missile shoot and everything, but it wont go forward, it will only stay in one spot when shot. Then it also won’t “die” so it takes up my hierarchy making it laggy.

For the missile maybe I should and a rigid-body to it so it will move?

var Shot : AudioClip;
var timer = 50;
var bulletspeed = 10;
var bullet : Transform;
	function Update () {
	if(timer == 50){
	if(Input.GetKey(KeyCode.Space)){
	audio.PlayOneShot(Shot);
	var bulletprefab : Transform;
	bulletprefab = Instantiate(bullet,
	transform.position, transform.rotation);
	timer = 0;
	}
	}
	else{
	timer += 1;
	}
	}

Thanks,
Wade

You gotta do ‘AddForce();’

Alright I’ll try :slight_smile: Thanks. Hopefully I can get it on the first try!

2 things.

  1. Please edit your post if the code doesn’t show up neatly.

  2. That code will only let you fire on 1 frame

Heres a version that will let you fire (it also added the movement and death)

var Shot : AudioClip;

var timeToFire : float=1.0f;
var bulletspeed = 10;
var bullet : Transform;
var bulletLifetime : float=10.0f;

private var timer : float;

function Start () {
	timer = timeToFire;
}

function Update () {
	if(timer >= timeToFire){
		if(Input.GetKey(KeyCode.Space)){
			audio.PlayOneShot(Shot);
			var bulletprefab : GameObject = Instantiate(bullet, transform.position, transform.rotation) as GameObject;
			
			bulletPrefab.rigidbody.AddForce (transform.forward*bulletSpeed);
			
			Destroy (bulletPrefab, bulletLifetime);
			
			timer = 0;
		}
	}
	else{
		timer += Time.deltaTime;
	}
}

For movement, you need a rigidbody, and you add force in the forward direction (using transform.forward)
To destroy it, you call Destroy (obj, lifeTime)

Alright thank you Dman. But there is a problem here it says:

bulletPrefab.rigidbody.AddForce (transform.forward*bulletSpeed);

“Unknown Identifier: bulletPrefab”.

EDIT: Never mind fixed it, just had to lowercase the S in speed and the P in prefab :slight_smile:

Thanks again.

Now it falls down when space has been pressed, but it wont shoot forward.

Maybe add a constant force?