Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Need some help with throwing an object using AddForce

Discussion in 'Scripting' started by Aaron Via, May 30, 2015.

  1. Aaron Via

    Aaron Via

    Joined:
    May 29, 2015
    Posts:
    6
    I am new to Unity and am going through the ropes and learning how to propel an object from my FPS-style camera angle. This has been mostly successful, however, I cannot seem to get the projectile to actually launch forward like I am trying to do. It merely drops right where it spawns. Here is my script:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Shooting : MonoBehaviour {
    5.     public GameObject bullet_prefab;
    6.     float detonatorspeed = 100f;
    7.     // Use this for initialization
    8.     void Start () {
    9.  
    10.     }
    11.  
    12.     // Update is called once per frame
    13.     void Update () {
    14.         Camera cam = Camera.main;
    15.         if (Input.GetButtonDown ("Fire1"))
    16.             Instantiate(bullet_prefab, cam.transform.position + cam.transform.forward, cam.transform.rotation);
    17.         bullet_prefab.GetComponent<Rigidbody> ().AddForce (cam.transform.forward * detonatorspeed, ForceMode.Impulse);
    18.          
    19.     }
    20. }
    21.  
    Any help would be much appreciated. I've seen other ways people are doing it with velocity, but I'd like to know how to solve this issue with this one. Keep in mind I'm getting no errors or bug reports, just something isn't working right.
    EDIT: I know in this script the last line of code is tabbed over to the left and not technically under the if( protocol, but it being in either place is still giving me the same result.
    Thanks.
     
    Last edited: May 30, 2015
  2. tomjoe

    tomjoe

    Joined:
    May 11, 2015
    Posts:
    44
  3. Aaron Via

    Aaron Via

    Joined:
    May 29, 2015
    Posts:
    6