- Home /
Question by
connorwforman · May 18, 2018 at 10:00 PM ·
scripting problemvector3shooting
Bullet only firing in 1 direction.
I am trying to make a bullet shoot in the direction a gun is pointing, but it just keeps firing in the global Vector3.forward
direction, not the way the gun is pointing. How would I make the bullet fire in the direction the gun is pointing?
public class AssaultRifle : MonoBehaviour {
public Rigidbody bullet;
public float ShootForce = 10f;
public GameObject gun_end;
public AudioSource ShotSound;
public GameObject playerEyes;
public float RateOfFire = 15f;
private float NextTimeToFire = 0f;
void Shoot () {
Rigidbody BulletClone = (Rigidbody)Instantiate(bullet, gun_end.transform.position, gun_end.transform.rotation);
BulletClone.velocity = Vector3.forward * ShootForce; //this is the place where the bullet should shoot in a straight line from gun_end, but it doesn't.
Instantiate(ShotSound, gun_end.transform.position, gun_end.transform.rotation);
}
void Update () {
if (Input.GetKey(KeyCode.Mouse0) && Time.time >= NextTimeToFire)
{
NextTimeToFire = Time.time + 1f / RateOfFire;
Shoot();
}
}
}
Comment
Answer by CranberryHorses · May 18, 2018 at 10:41 PM
You might need to try
BulletClone.velocity = transform.TransformDirection(Vector3.forward * ShootForce);
Or some variation of that. I got that code from the unity API Here