Shoot to Mouse position

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.

public class Projectiles : MonoBehaviour
{

    public float force ;
    public GameObject bulletPrefab;
    public GameObject gunEnd;
    private Vector3 aim;
    // Update is called once per frame
    void Update()
    {

        

        Vector3 mousePos = Input.mousePosition;
        mousePos += Camera.main.transform.forward * -10f; // Make sure to add some "depth" to the screen point
        aim = Camera.main.ScreenToWorldPoint(mousePos);
        if (Input.GetKey(KeyCode.Mouse0)  )
        {
            gunEnd.transform.LookAt(aim);
            GameObject bullet = Instantiate(bulletPrefab, gunEnd.transform.position, Quaternion.identity);
            bullet.transform.LookAt(aim);
            Rigidbody b = bullet.GetComponent<Rigidbody>();
            b.AddRelativeForce(Vector3.forward * force);
            
        }
    }
       
}

Well you’re multiplying the forward vector by -10, so that’s no surprise. Try this instead:

Camera cam = Camera.main;

Vector3 mousePos = Input.mousePosition;
aim = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
2 Likes

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.

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?

I retried your code and this is what I’ve got. The camera is set on a path thats why it rotated.

public class Projectiles : MonoBehaviour
{


    public float force;
    public GameObject bulletPrefab;
    public GameObject gunEnd;
    private Vector3 aim;
   
    // Update is called once per frame
    void Update()
    {




        Camera cam = Camera.main;

        Vector3 mousePos = Input.mousePosition;
        aim = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));

        if (Input.GetKey(KeyCode.Mouse0))
        {
              

   
              GameObject bullet = Instantiate(bulletPrefab, aim, Quaternion.identity);
       

            Rigidbody b = bullet.GetComponent<Rigidbody>();
            b.AddRelativeForce(  transform.forward  * force);

        }
    }

}

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).

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.

  Vector3 mousePos = Input.mousePosition;
            mousePos += Camera.main.transform.forward * 10f; // Make sure to add some "depth" to the screen point
           aim = Camera.main.ScreenToWorldPoint(mousePos);

   

        if (Input.GetKey(KeyCode.Mouse0))
        {
                gunEnd.transform.LookAt(aim );

              GameObject bullet = Instantiate(bulletPrefab, gunEnd.transform.position, Quaternion.identity);
            
               bullet.transform.LookAt(aim);
        

            Rigidbody b = bullet.GetComponent<Rigidbody>();
            b.AddRelativeForce(  -transform.forward  * force);

        }

https://www.youtube.com/watch?v=E-OEfTdpFnA

this does not seem to work for me. Do I have to do something outside of this script?

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.