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. Dismiss Notice

Shoot to Mouse position

Discussion in 'Scripting' started by MathewHI, Jun 7, 2021.

  1. MathewHI

    MathewHI

    Joined:
    Mar 29, 2016
    Posts:
    501
    Does anyone know what the problem is with this code? I've got a player on a rail path in first person and trying to shoot a projectile towards the mouse position. This code is working except its shooting from the mouse position backwards I need to change the direction 180 degrees.

    Code (CSharp):
    1. public class Projectiles : MonoBehaviour
    2. {
    3.  
    4.     public float force ;
    5.     public GameObject bulletPrefab;
    6.     public GameObject gunEnd;
    7.     private Vector3 aim;
    8.     // Update is called once per frame
    9.     void Update()
    10.     {
    11.  
    12.        
    13.  
    14.         Vector3 mousePos = Input.mousePosition;
    15.         mousePos += Camera.main.transform.forward * -10f; // Make sure to add some "depth" to the screen point
    16.         aim = Camera.main.ScreenToWorldPoint(mousePos);
    17.         if (Input.GetKey(KeyCode.Mouse0)  )
    18.         {
    19.             gunEnd.transform.LookAt(aim);
    20.             GameObject bullet = Instantiate(bulletPrefab, gunEnd.transform.position, Quaternion.identity);
    21.             bullet.transform.LookAt(aim);
    22.             Rigidbody b = bullet.GetComponent<Rigidbody>();
    23.             b.AddRelativeForce(Vector3.forward * force);
    24.            
    25.         }
    26.     }
    27.        
    28. }
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Well you're multiplying the forward vector by -10, so that's no surprise. Try this instead:
    Code (csharp):
    1.  
    2. Camera cam = Camera.main;
    3.  
    4. Vector3 mousePos = Input.mousePosition;
    5. aim = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
    6.  
     
    Mirbo and Kurt-Dekker like this.
  3. MathewHI

    MathewHI

    Joined:
    Mar 29, 2016
    Posts:
    501
    Hi sir I tried your code thank you. With yours the gameobject was just stuck in place it didn't move.

    I changed the -10 to 30 and its firing at the mouse now but the projectiles never hit the center of the crosshair, they are always slightly off, down and to the right. Around 30 is the closest I could get them but they are not going to center.
     
  4. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Odd. It should spawn exactly where your cursor is.

    Can you share your updated code and post any sort of images/videos of it in action?
     
  5. MathewHI

    MathewHI

    Joined:
    Mar 29, 2016
    Posts:
    501
    I retried your code and this is what I've got. The camera is set on a path thats why it rotated.

    Code (CSharp):
    1. public class Projectiles : MonoBehaviour
    2. {
    3.  
    4.  
    5.     public float force;
    6.     public GameObject bulletPrefab;
    7.     public GameObject gunEnd;
    8.     private Vector3 aim;
    9.    
    10.     // Update is called once per frame
    11.     void Update()
    12.     {
    13.  
    14.  
    15.  
    16.  
    17.         Camera cam = Camera.main;
    18.  
    19.         Vector3 mousePos = Input.mousePosition;
    20.         aim = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
    21.  
    22.         if (Input.GetKey(KeyCode.Mouse0))
    23.         {
    24.              
    25.  
    26.    
    27.               GameObject bullet = Instantiate(bulletPrefab, aim, Quaternion.identity);
    28.        
    29.  
    30.             Rigidbody b = bullet.GetComponent<Rigidbody>();
    31.             b.AddRelativeForce(  transform.forward  * force);
    32.  
    33.         }
    34.     }
    35.  
    36. }
    37.  
     
  6. Boo-Let

    Boo-Let

    Joined:
    Jan 21, 2019
    Posts:
    150
    Try setting the bullet to instantiate in a fixed area. Something like a muzzle position. Then use the cursor to draw a ray cast out into the scene a fixed distance. Typically the weapons range. (So if your weapon range is 50 draw a ray to 50). Then use the ray point as an end point. (Cursor position + ray distance).

    Fire the projectile from point A (muzzel) to point B (ray cast vector).
     
  7. MathewHI

    MathewHI

    Joined:
    Mar 29, 2016
    Posts:
    501
    Actually I ended up doing it this way, I wanted it to look like the bullets were being lobbed into the screen. I actually do have a raycast at the crosshair position thats how I'm detecting hitting something the bullets are just visual.

    Code (CSharp):
    1.   Vector3 mousePos = Input.mousePosition;
    2.             mousePos += Camera.main.transform.forward * 10f; // Make sure to add some "depth" to the screen point
    3.            aim = Camera.main.ScreenToWorldPoint(mousePos);
    4.  
    5.    
    6.  
    7.         if (Input.GetKey(KeyCode.Mouse0))
    8.         {
    9.                 gunEnd.transform.LookAt(aim );
    10.  
    11.               GameObject bullet = Instantiate(bulletPrefab, gunEnd.transform.position, Quaternion.identity);
    12.            
    13.                bullet.transform.LookAt(aim);
    14.        
    15.  
    16.             Rigidbody b = bullet.GetComponent<Rigidbody>();
    17.             b.AddRelativeForce(  -transform.forward  * force);
    18.  
    19.         }
     
  8. FireJojoBoy

    FireJojoBoy

    Joined:
    Oct 30, 2019
    Posts:
    65
    this does not seem to work for me. Do I have to do something outside of this script?
     
  9. MathewHI

    MathewHI

    Joined:
    Mar 29, 2016
    Posts:
    501
    New
    Sorry but yes you will, that code right there is just to have the visual projectiles be seen and placed into the scene. My actual firing code where you pull the trigger is on another script ,sorry for the confusion. I got the firing code from a tutorial which uses a raycast but I wanted to add visual projectiles so I added this. The system is a little too involved to paste here but if it helps you essentially I cast a ray like this:

    if(Physics.Raycast(ray, hit, 50f, layerMask)

    to detect if it intersects anything. There are a lot of tutorials on raycasts you'll have to apply it to fit your own game.