Script - Shoot towards the mouse pointer

Hi folks,

I’ve got a small 2D project going to help me learn Unity and C#. I have no previous experience, and have only been at this a few weeks so please be patient :slight_smile:

Here’s where I’m up to and what I’m trying to accomplish.

I have a player object, and a laser prefab.

I’ve got the code sorted to instantiate the laser prefab and fire it off to the right. This continues then destroys itself when it’s out of scene. It works fine.

What I want to do however, is change this so that the laser is fire in the direction the mouse is pointing when it’s fired. I’ve googled a few different phrases and looked at a few different results that came up, but none of it makes any sense to me I’m afraid!

I’ve have a Player script that controls that, and a Laser script. Here’s what’s in both of them.

If anyone knows of a tutorial, or guide, or can give me some guidance on how to accomplish what I’m trying to do that would be extremely helpful. Thanks.

Player Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{

    [SerializeField]
    private float fireRate = 0.1f;
    // fire rate variable
    private float canFire = 0.0f;
    // checks if the time has passed to allow firing again - prevents spamming fire
    [SerializeField]
    private GameObject _laserPrefab;
    [SerializeField]
    private float speed = 6.0f;

    // Start is called before the first frame update
    void Start()
    {
        transform.position = new Vector3(0, -2.0f, 0);
    }

    // Update is called once per frame
    void Update()
    {
        Movement();
        if (Input.GetMouseButtonDown(0))
        {
            shoot();
        }
    }

    private void Movement()
    {
        float horizontalInput = Input.GetAxis("Horizontal");

        transform.Translate(Vector3.right * speed * horizontalInput * Time.deltaTime);
    }

    private void shoot()
    {
        if (Time.time > canFire)
        {
           Instantiate(_laserPrefab, transform.position + new Vector3(1, 0, 0), Quaternion.identity);
        }
        canFire = Time.time + fireRate;
      
    }
}

Laser
```csharp
**using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Laser : MonoBehaviour
{
[SerializeField]
private float _speed = 10.0f;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    transform.Translate(Vector3.right * _speed * Time.deltaTime);
    // destroy laser object when it goes out of screen
    if (transform.position.x >= 10.0f)
    {
        if (transform.parent != null)
        {
            Destroy(transform.parent.gameObject);
        }
        Destroy(this.gameObject);
    }

}

}**
```

Second script, see line 18? You are moving by Vector3.right (times your speed, times the deltaTime so it is frame independent).

Vector3.right is the unit vector (1,0,0), which makes your bullet go right.

What you need instead is a unit vector that will go from the muzzle of the gun to the intended impact point where your mouse clicked.

You can use the camera and raycast into the screen to find where the mouse clicked. There’s TONS of examples of that step out there on the web so I won’t go into that.

Now lets say you have clicked the mouse and figured out where the bullet destination should be:

// you have stored the bullet destination here:
Vector3 BulletDestination;

// and this is a reference to the player:
Transform ThePlayerTransform;

Now, what is the gap between click point and where the player is?

Vector3 Difference = BulletDestination - ThePlayerTransform.position;

The variable ‘Difference’ will now contain the difference (in vector3 format) between the player and the click point.

Now you need to make that unit vector!

Vector3 BulletTravelDirection = Difference.normalized;

Finally you will now use the BulletTravelDirection in place of the Vector3.right in line 18 above.

You will need to check for other things besides “>= 10.0f” because it could go off in any direction.

One way to kill bullets is to put a script on them that only lets them go for a second or two, then kills them.

1 Like

Thank you, I will look up some of those ray casting examples and have another crack at this.

I think I need to figure out how to Google things better!