Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

RayCast Bullet

Discussion in 'Scripting' started by aljstevens, May 1, 2019.

  1. aljstevens

    aljstevens

    Joined:
    Mar 15, 2019
    Posts:
    16
    Hello,

    I am trying to set up a crosshair for my game. I know I can use a raycast find the position where I click. However I'm having troubles figuring out how to make the bullet move from the player to that clicked location.

    As well I can't figure out what happens if the player shoots at the sky how to get that information for the raycast.


    Does anyone know a way to achieve these?
     
  2. ChrisBannoura

    ChrisBannoura

    Joined:
    Feb 19, 2018
    Posts:
    21
    Can I see your code?
     
    aljstevens likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,798
    If your bullet is instantaneous, then you just raycast to see if you hit anything.

    If you hit anything, additional info can be returned in the RaycastHit object.

    You can use that to:

    - decide who/what you hit (via name, type, tag, layer, etc.)
    - draw a bullet splash
    - draw a bullet streak for that one frame

    Firing at the sky would likely make you hit nothing with the raycast.

    As always you can use Layers to mask out what layers you don't care about. There's plenty of examples if you google.

    If your bullet is going to travel over several frames then ALL of the above applies, except you do it iteratively:

    - move the bullet how far it goes in one frame
    - see if it hit anything, then you're done
    - draw the streak so far
    - adjust its motion to accommodate gravity

    Repeat until you hit or bullet travels your max range.
     
    aljstevens and SparrowGS like this.
  4. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Are we talking first person or what?

    first of all, most games don't actually send bullets flying though the air, they figure out what they would have shot with a raycast from the gun barrel (or the HUD rect on screen for example) and communicate the damage with it.

    you could of course send a rigidbody on a ballistic trajectory simulating a bullet, but it would be a lot of overhead in a bullet hell, it could be useful for sniper action and alike though, where you don't have much bullets and big spaces.
    (you can use multiple raycasts to simulate an arc instead of a straight line)

    edit: and you can make it take a bit of time like @Kurt-Dekker mentioned even with raycasts

    I would guess a few, yeah (;
     
    aljstevens and Kurt-Dekker like this.
  5. aljstevens

    aljstevens

    Joined:
    Mar 15, 2019
    Posts:
    16
    Thanks guys I got it. Just needed to read this stuff to jog my memory.

    Code (CSharp):
    1.     if(Input.GetButtonDown("Fire1"))//  && Timer <=0)
    2.         {
    3.             Ray ray;
    4.             RaycastHit hit;
    5.             ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    6.  
    7.             if (Physics.Raycast(ray, out hit))
    8.             {
    9.                 Target = Instantiate(HitPoint, hit.point, Quaternion.identity) as GameObject ;
    10.                 Bullet = Instantiate (Spell, gameObject.transform.position, gameObject.transform.rotation) as GameObject ;
    11.                 Bullet.transform.LookAt (new Vector3 (Target.transform.position.x, Target.transform.position.y, Target.transform.position.z));
    12.                 //Timer = TimerAmount;
    13.             }
    14.  
    15.         }
    I ended up doing this, and putting invisible colldiers in the sky, so the player could shoot there. My last problem was I was forgetting that it's the tip of the cursor is where the hit information is added. So I just moved my crosshairs. Thanks guys a lot :D
     
  6. aljstevens

    aljstevens

    Joined:
    Mar 15, 2019
    Posts:
    16
    Also it was a third person shooter
     
  7. Boz0r

    Boz0r

    Joined:
    Feb 27, 2014
    Posts:
    419
    You should look into object pooling. All those Instantiates are going to hurt your performance in the long run.
     
  8. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,745
    If you want to detect specific case when player shooting in the sky, place invisible box collider up there and if raycast hitted that collider, then you can be sure player was targeting the sky.
     
  9. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @aljstevens

    "I ended up doing this, and putting invisible colldiers in the sky, so the player could shoot there."


    You can also define maximum distance for a raycast, if you don't need to know for sure that you hit sky like
    @palex-nx said.

    Set raycast maximum distance to something big that suits your game level, if your ray hits before this, you have an environment hit, if not, you are aiming is towards sky.

    Code (CSharp):
    1. if (Physics.Raycast(shootingRay, out bulletHit, hitDistance, raycastLayer))
    2. {
    3.    // hit environment
    4. }
    5.  
     
  10. AndersMalmgren

    AndersMalmgren

    Joined:
    Aug 31, 2014
    Posts:
    5,358
    You should always use maximum distance for performance. There is no reason to use colliders in sky for this.

    I'm working on ballistics on and off for our game. You can shoot straight up and the bullet will return thanks to gravity . Need to implement steam achievements just for the achievement to kill a enemy player with a returning bullet :)
     
  11. aljstevens

    aljstevens

    Joined:
    Mar 15, 2019
    Posts:
    16
    Even if I have them delete after like 5 seconds?
     
  12. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    That's exactly the problem, instead of allocating new room for a new object and cleaning up old ones, you re-use the old ones saving time, it does require what ever is being pooled to be able to revert back to it's original("prefab") state.

    look into it, it's worth while, but know where to apply it.
     
  13. Boz0r

    Boz0r

    Joined:
    Feb 27, 2014
    Posts:
    419
    Especially when you only use them for 5 seconds. Instatiating and destroying is time consuming, simply disabling the object is not.
     
  14. Sanjay112000

    Sanjay112000

    Joined:
    Nov 9, 2020
    Posts:
    10
    Here is my solution.

    Make sure cross hair at center of screen.
    make sure camera is also in center of screen

    Here is the shoot function

    RaycastHit hit;
    if (Physics.Raycast(instantiationSpot.transform.position,mainCamera.transform.forward, out hit, 2500,layerMask))
    {
    // Debug.Log(hit.collider.name+"has been shot");


    // bullet instantiation
    Rigidbody bulletClone = this.GetComponent<bulletPooling>().getBullet(instantiationSpot.transform.position,Quaternion.LookRotation(hit.normal)).GetComponent<Rigidbody>();
    //setting velocity such that it reaches destination
    bulletClone.velocity =( hit.point - instantiationSpot.transform.position ).normalized * 10;



    }