Sage Hopkins
Sage Hopkins

Reputation: 173

Gun Script Creates Bullet But Bullet Travel in All Different Directions

Bullet Going Everwhere Except Straight

I am trying to create a gun script however after the bullet prefab instantiates, it doesn't travel in the correct direction(Straight). The function used to create bullets in Shoot() which is called when the Update loop gets the input from GetMouseButton(0).

  public class CharController : MonoBehaviour {

    [SerializeField]
    float moveSpeed = 4f;

    public float aimSpeed;
    Vector3 mousePos;

    Vector3 forward, right;
    public GameObject bulletSpawnPoint;
    public GameObject bullet;
    public float bullet_Speed;
    public float fireRate;

    void Start () {

        forward = Camera.main.transform.forward;
        forward.y = 0;
        forward = Vector3.Normalize(forward);
        right = Quaternion.Euler(new Vector3(0, 90, 0)) * forward;
    }

    void Update () {
        if (Input.GetMouseButton(0))
        {
            transform.position += (-transform.position + mousePos).normalized * aimSpeed * Time.deltaTime;
            transform.position = new Vector3(transform.position.x, 2.5f, transform.position.z);

            Shoot();
        }

    }

    void Shoot()
    {
        GameObject temp_Bullet_Handler;
        temp_Bullet_Handler = Instantiate(bullet, bulletSpawnPoint.transform.position, bulletSpawnPoint.transform.rotation) as GameObject;

        //temp_Bullet_Handler.transform.Rotate(Vector3.left * 90);

        Rigidbody temp_Rigidbody;

        temp_Rigidbody = temp_Bullet_Handler.GetComponent<Rigidbody>();
        temp_Rigidbody.AddForce(Vector3.forward * Time.deltaTime * 10f);

        Destroy(temp_Bullet_Handler, 10.0f);



    }

}

If anyone has any information on what causes the bullets not to travel in a straight direction from the instantiation point, I would love to have your input.

Thanks in advance

Upvotes: 0

Views: 103

Answers (1)

Dan Bystr&#246;m
Dan Bystr&#246;m

Reputation: 9244

Your Update moves the bullet in a direction which is based on it's position. Change that into a direction vector, like your "forward" instead of transform.position.

Upvotes: 1

Related Questions