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

Question FPS raycast shooting

Discussion in 'Scripting' started by igero, Jan 15, 2022.

  1. igero

    igero

    Joined:
    Jul 8, 2019
    Posts:
    1
    Hi. I'm trying to create shooting system in my project. I would like to do it like in this video from Unreal Engine. So I want to create first static raycast from gun barrel to center of screen and second raycast from barrel to center of screen but it will be moving with gun.



    I've tried many methods from forums and other videos but I can't reach my wanted effect. Actual code:

    Code (CSharp):
    1.     void OnDrawGizmosSelected()
    2.     {
    3.  
    4.         Ray ray = new Ray(muzzle.position, muzzle.forward); //muzzle is end of the gun
    5.         RaycastHit hit;
    6.  
    7.         if(Physics.Raycast(ray, out hit))
    8.         {
    9.             Gizmos.color = Color.blue;
    10.             Gizmos.DrawLine(ray.origin, GetHitPoint(muzzle.position));
    11.         }    
    12.     }
    13.  
    14.     //code from forum for test
    15.     Vector3 GetHitPoint(Vector3 muzzlePosition) {
    16.         // Unless you've mucked with the projection matrix, firing through
    17.         // the center of the screen is the same as firing from the camera itself.
    18.         Ray crosshair = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
    19.  
    20.         // Cast a ray forward from the camera to see what's
    21.         // under the crosshair from the player's point of view.
    22.         Vector3 aimPoint;
    23.         RaycastHit hit;
    24.         if(Physics.Raycast(crosshair, out hit, 30)) {
    25.             aimPoint = hit.point;      
    26.         } else {
    27.             aimPoint = crosshair.origin + crosshair.direction * 30;
    28.         }
    29.  
    30.         // Now we know what to aim at, form a second ray from the tool.
    31.         Ray beam = new Ray(muzzlePosition, aimPoint - muzzlePosition);
    32.  
    33.         // If we don't hit anything, just go straight to the aim point.
    34.         if(!Physics.Raycast(beam, out hit, 30))
    35.             return aimPoint;
    36.  
    37.         // Otherwise, stop at whatever we hit on the way.
    38.         return hit.point;
    39.     }
    Also I have a problem with raycast when I'm close to the wall. Right now it looks like on this screen :(
    screen.png

    Any ideas?
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,646
    Well, you can either shoot the Raycast out of the gun, or you can shoot the Raycast out of the camera. You can't really shoot a Raycast from the gun to the middle of the camera, unless they were lined up.