Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Addforce to bullet pushes player rigidbody back as well [Solved]

Discussion in 'Scripting' started by Troas, Jul 2, 2014.

  1. Troas

    Troas

    Joined:
    Jan 26, 2013
    Posts:
    157
    So I'm sure I'm missing something pretty basic here but I'm having a problem with my player being pushed back whenever he fires a bullet.

    How do I negate this force and have it add to the bullet only so the player can move independently?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class BulletFire : MonoBehaviour {
    5.  
    6.     public float bulletSpeed = 8;
    7.    
    8.     public Transform bullet;
    9.  
    10.     void Start () {
    11.     }
    12.  
    13.     void FixedUpdate () {
    14.         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    15.         RaycastHit hit = new RaycastHit();
    16.  
    17.         if (Physics.Raycast (ray, out hit, 100)) {
    18.         }
    19.  
    20.         if (Input.GetMouseButtonDown (0)) {
    21.             Debug.Log("Left Button Clicked");
    22.             Fire ();
    23.         }
    24.     }
    25.  
    26.  
    27.  
    28.     void Fire () {
    29.         GameObject obj = ObjectPooler.current.GetPooledObject();
    30.  
    31.         if (obj == null)return;
    32.         obj.transform.position = transform.position;
    33.         obj.transform.rotation = transform.rotation;
    34.         obj.SetActive (true);
    35.  
    36.         rigidbody.velocity = bullet.transform.forward * bulletSpeed;
    37.     }
    38. }
    39.  
    Object Pooling method is from the live training (thank you so much for that one).
     
  2. rrh

    rrh

    Joined:
    Jul 12, 2012
    Posts:
    331
    So you attach this BulletFire class to the player, on the basis that the player fires bullets?

    And in your Fire funciton, "obj" is the new bullet?

    obj.rigidbody.velocity = obj.transform.forward * bulletSpeed;
     
    Troas likes this.
  3. Troas

    Troas

    Joined:
    Jan 26, 2013
    Posts:
    157
    Thanks I actually just figured that out after looking at it, now onto more problems haha!