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

Raycast Problem

Discussion in 'Scripting' started by ahaykal, Nov 28, 2012.

  1. ahaykal

    ahaykal

    Joined:
    Apr 18, 2010
    Posts:
    117
    Hey guys,

    I am having trouble trying to figure out how to fix this problem.

    I have a fire breath that shoots at the location of the mouse, now it follows the mouse's rotation, however its instantiating at the wrong place. I will show you what I mean:
    When I press up look at where it is instantiating
    [/IMG]


    When I press in the bottom region there instantiates



    Could you please guide me to the right way?
    Here is my code.
    Code (csharp):
    1.  
    2. var lookTarget : Vector3;
    3.  
    4. var FireProjectilePrefab : GameObject;
    5. var hitdist = 0.0;
    6. var power : int = 10;
    7. var OneShot : int = 0;
    8.  
    9.  
    10. function Update()
    11. {
    12.  
    13. var hit  : RaycastHit ;
    14.     if(Input .GetButtonDown ("Fire1"))
    15.     {
    16.        var ray : Ray  = Camera .main .ScreenPointToRay (Input .mousePosition );
    17.        var clone : GameObject;
    18.        
    19.        
    20.        if(Physics.Raycast (ray, hit, Mathf.Infinity))
    21.        {
    22.        var targetPoint = ray.GetPoint(hitdist);
    23.        var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);     
    24.        
    25.             if(OneShot == 0)
    26.             {  
    27.            
    28.                 transform.rotation = targetRotation;
    29.                 clone = Instantiate(FireProjectilePrefab, transform.position, Quaternion.identity);
    30.                
    31.                 clone.transform.rotation.x = targetRotation.x ;
    32.                 clone.transform.rotation.z = targetRotation.z;
    33.             }
    34.            
    35.            
    36.                 if(OneShot>=1)
    37.                 {
    38.            
    39.                 Destroy(GameObject.FindGameObjectWithTag("Stream"));
    40.                 clone = Instantiate(FireProjectilePrefab, transform.position, Quaternion.identity);        
    41.                
    42.                 clone.transform.rotation.z = targetRotation.z;
    43.                 clone.transform.rotation.x = targetRotation.x ;
    44.                
    45.                 }
    46.                         }
    47.        
    48.        }
    49.     }
    50.  
    51.  
    Thanks in advance