Search Unity

projectile not firing properly

Discussion in 'Scripting' started by 8r3nd4n, Oct 24, 2011.

  1. 8r3nd4n

    8r3nd4n

    Joined:
    Sep 10, 2011
    Posts:
    30
    Hi guys

    I am having some trouble getting a projectile to fire how I am after.
    What I have is a crosshair that remains stationary in the center of the screen where the projectile will fire through (firePosition).
    By using the mouse, they can drag to an x,y point in the screen with a z position about 3 behind the crosshair (handPosition).
    Then when they fire, the projectile will go from the mouse position and through the crosshair using the 2 different positions to work out the angle of the shot.

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ProjectileFire : MonoBehaviour {
    5.    
    6.     public float shootForce;
    7.     public Transform target;
    8.     Vector3 firePosition;
    9.     Vector3 handPosition;
    10.     public GameObject projectilePrefab;
    11.     // Use this for initialization
    12.     void Start () {
    13.    
    14.         firePosition = new Vector3(0,3,0);
    15.     }
    16.    
    17.     // Update is called once per frame
    18.     void Update () {
    19.    
    20.         transform.LookAt(target);
    21.        
    22.         if (Input.GetMouseButtonDown(0))
    23.         {
    24.            
    25.         }
    26.        
    27.         if (Input.GetMouseButtonUp(0))
    28.         {
    29.                 handPosition = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x,Input.mousePosition.y,3.0f));
    30.             Instantiate (projectilePrefab,handPosition,Quaternion.identity);
    31.             projectilePrefab.rigidbody.AddForce(transform.forward * shootForce);
    32.         }
    33.     }
    34. }
    35.  
    Any suggestions?
    Thanks