- Home /
Bullet doesn't go forward
It spawns (although I think the recoil thing doesn't work), but then it just stays in the same position.
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour {
public float recoil = 0.5f;
public GameObject bullet;
private int counter;
void Start(){
counter = 0;
}
void Update () {
if (Input.GetButton ("Fire1")) {
counter++;
Instantiate (bullet, transform.position, transform.rotation);
bullet.transform.Rotate (0, -recoil*counter, 0);
bullet.GetComponent<Rigidbody> ().AddForce (transform.forward * 10000);
} else
counter = 0;
}
}
Answer by _joe_ · Apr 15, 2015 at 01:24 PM
Here you go, you've had several issues, you should use GetButtonDown instead of GetButton to get one call per click.
You need to instantiate and save the instantiated object in a variable and assign the rotate and add force to the variable (instead of the prefab reference which is not the actual object).
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour {
public float recoil = 0.5f;
public GameObject bullet;
private int counter;
void Start(){
counter = 0;
}
void Update () {
if (Input.GetButtonDown ("Fire1")) {
counter++;
GameObject myBullet = Instantiate (bullet, transform.position, transform.rotation) as GameObject;
myBullet.transform.Rotate (0, -recoil*counter, 0);
myBullet.rigidbody.AddForce (Vector3.forward * 500);
} else
counter = 0;
}
}
Answer by MitchWardle180 · Jun 03, 2015 at 01:14 PM
I would create a bullet script and place it on the prefab instantiated and control the bullet movement from the script. You could set a muzzle velocity variable and have it change based on which weapon you are using causing a gun to shoot faster/slower than another. Also if you use a bullet script it would also be easier to apply drop and air friction to the bullet.
WOULD AVOID USING 'rigidbody.AddForce()' FOR BULLETS BECAUSE IF THE BULLET MOVES MORE THAN THE SIZE OF THE OBJECT THE COLLISION DETECTION FOR IT WOULD BE TERRIBLE*
Answer by wenbo · May 04, 2015 at 10:11 AM
In my idea,it's better not use AddForce function,but attach a script on the bullet,in the script's update function,use logic function to make the bullet fly.This is assignment of responsibility,which will make you logic more clear.
Your answer
Follow this Question
Related Questions
RigidBody.MovePosition seems jerky in movement 0 Answers
Distribute terrain in zones 3 Answers
Don't allow the player to shoot while projectile is travelling 1 Answer
How does instantiate connect to rigidbody?,How does instantiate userigidbody without getcomponent? 1 Answer
Multiple Cars not working 1 Answer