Hi so I’m new to Unity and I was watching a tutorial on how to make a gun shoot and copied the code he used. This is the script for the bullets to spawn (javascript)
var projectile : Rigidbody;
var speed = 20;
function Update () {
if ( Input.GetButton ("Fire1")) {
clone = Instantiate(projectile, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection( Vector3 (0, 0, speed));
Destroy (clone.gameObject, 3);
}}
I’m not much of programmer, but the way he explained it I kind of understand it a bit. So this is my question, when I press the mouse button to shoot it, it makes a lot of copys of the object I have for the bullet, because of this unless I increase the speed to a high number they don’t go straight. Is there anyway I can lower the amount of bullets that spawn?
var bullet : Rigidbody;
var fireRate : float = 1;
var bulletSpeed : float = 1;
private var nextFireTime : float;
function Start() {
nextFireTime = Time.time+fireRate;
}
function Update() {
if(Input.GetButton("Fire1")) {
Fire();
}
}
function Fire() {
if(Time.time - fireRate > nextFireTime) {
FireOnce();
nextFireTime = Time.time+fireRate;
}
}
function FireOnce() {
var projectile = Instantiate(bullet, transform.position, transform.rotation);
projectile.rigidbody.velocity = transform.TransformDirection(Vector3.forward) * bulletSpeed;
Physics.IgnoreCollision(projectile.collider, transform.root.gameObject.collider);
Destroy(projectile.gameObject, 3);
}
This is what I use (modified to fit your codes standards).
Basically, you need to add a check for the Time.time. I trust you can see how this works by looking at my code.
I also have a Physics.IgnoreCollision to ignore collision with the root gameObject (top of the heirarchy). Otherwise, the bullets may go in random directions if they spawn inside of the player.
If your weapon has a collider as well, you will have to IgnoreCollision on its collider too.
Dman
Can you give me example (prefab file), where bullet collides with enemy, when bullet velocity is very fast.
In my code when i set my bullet very fast speed collide doesn’t work with enemy and bullet flying through enemy
Thanks