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

Allowing player to aim gun with raycasts

Discussion in 'Scripting' started by romans8710, Apr 9, 2020.

  1. romans8710

    romans8710

    Joined:
    Mar 29, 2020
    Posts:
    7
    I have a working pistol (3d) that spawns bullets with velocity when the left button is pressed and I also have a 2D crosshair that is positioned at the centre of the camera. The problem is that when I shoot bullets they naturally go off target as the pistol is slightly to the right of the camera and not in the centre of the camera like the crosshair. I’ve heard that using raycasts can help this but am unsure how, any thoughts?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    You don't really need raycasts of any kind. Just spawn the bullet at "theCamera.transform.position" with rotation "theCamera.transform.rotation" and set its velocity to "speed * theCamera.transform.forward"
     
  3. romans8710

    romans8710

    Joined:
    Mar 29, 2020
    Posts:
    7
    Wouldn’t this make the bullet appear to be coming from the players eyes and not the barrel of the gun?
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Ah ok I see. So what you want is for the bullet to still come from the gun, which is off center, but you want it to travel at what the camera is looking at? Yes you can use raycasts for this. Something like:

    Code (CSharp):
    1.         RaycastHit hit;
    2.         Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
    3.  
    4.         Vector3 hitPoint;
    5.         if (Physics.Raycast(ray, out hit)) {
    6.            hitPoint = ray.GetPoint(hit.distance);
    7.         } else {
    8.            hitPoint = ray.GetPoint(10000/* or some very far distance */);
    9.         }
    10.  
    11.         Vector3 bulletDirection = hitPoint - bulletSpawnPoint;
    You can then assign your bullet velocity and rotation based on the bulletDirection vector. This way it will travel towards what your camera is looking at.
     
    romans8710 likes this.
  5. APSchmidtOfOld

    APSchmidtOfOld

    Joined:
    Aug 8, 2016
    Posts:
    4,473
    Did you search the Lean section for "shooting with raycasts"?

    https://learn.unity.com/tutorial/let-s-try-shooting-with-raycasts#
     
  6. romans8710

    romans8710

    Joined:
    Mar 29, 2020
    Posts:
    7
    Ok thank you!