Search Unity

Bullet to move along Raycast

Discussion in 'Scripting' started by FinlayHanlon, Jul 29, 2014.

  1. FinlayHanlon

    FinlayHanlon

    Joined:
    Dec 10, 2013
    Posts:
    46
    Hi, I'm trying to get it so my bullet moves along the raycast when i press Fire1 in this javascript. Its attached to my main camera which is a child of my third person character. A couple of things, 1) Nothing actually happens when i press fire1, i'm expecting to see my bullet travel along the raycast, 2) does it have to be a rigidbody or a transform for the bullet to appear? Its giving me the NullReferenceException: Object reference not set to an instance of an object at line 10 and 12, is this my problem? - and can someone explain what that error means?

    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var projectile : Rigidbody;
    4. var speed = 20;
    5.  
    6. function Update () {
    7.     if (Input.GetButtonDown("Fire1"))
    8.     {
    9.     var hit : RaycastHit;
    10.     var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5));      
    11.        
    12.         if (Physics.Raycast (ray, hit))
    13.         {
    14.             Debug.DrawLine(transform.position, hit.point, Color.red);
    15.             Debug.Log(hit.point);
    16.             var instantiatedProjectile : Rigidbody = Instantiate(projectile, transform.position, transform.rotation);
    17.             instantiatedProjectile.velocity = (hit.point - transform.position).normalized * speed;
    18.             instantiatedProjectile.rotation = Quaternion.LookRotation(instantiatedProjectile.velocity);
    19.         }
    20.     }
    21. }
     
  2. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    Instantiate GameObjects, not Rigidbodies. Also, does the raycast actually hit something? Why do you want to use raycast for firing bullets?
     
  3. FinlayHanlon

    FinlayHanlon

    Joined:
    Dec 10, 2013
    Posts:
    46
    Well, what i was trying to do was to get it so that the bullet travels in a straight line along the raycast - without being affected by gravity. I had a script before i did that which used instantiate - i could never get it so i travels in a straight line without being affected by gravity - and that script did require a rigidbody on the bullet in order for it to fire.
     
  4. BottomGames

    BottomGames

    Joined:
    Jun 23, 2012
    Posts:
    28
    All you have to do is turn off the gravity in the inspector for the instantiated object in this case the bullet. Look under rigid body component and uncheck "use gravity" that should do it. You wont need to use the rayscast at that point.
     
  5. keenanwoodall

    keenanwoodall

    Joined:
    May 30, 2014
    Posts:
    598