Unity Point and ShootHow to shoot in the direction of the mouse

Author Waldo
Published April 1, 2019

In this tutorial we discuss how to point and shoot a turret towards the direction of your mouse.

Video Walkthrough

  • 0:50 - Creating a C# Script
  • 1:40 - Calculating our target position
  • 2:04 - Crosshairs following mouse movement
  • 2:40 - Hiding our mouse cursor 
  • 3:15 - Rotating our gun to point towards the mouse
  • 4:25 - Creating an anchor point for our turret
  • 5:00 - Firing a projectile on click
  • 8:40 - Showing off the finished product

Source Code for PointAndShoot.cs

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

public class PointAndShoot : MonoBehaviour {
    public GameObject crosshairs;
    public GameObject player;
    public GameObject bulletPrefab;
    public GameObject bulletStart;

    public float bulletSpeed = 60.0f;

    private Vector3 target;

    // Use this for initialization
    void Start () {
        Cursor.visible = false;
    }
    
    // Update is called once per frame
    void Update () {
        target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
        crosshairs.transform.position = new Vector2(target.x, target.y);

        Vector3 difference = target - player.transform.position;
        float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        player.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);

        if(Input.GetMouseButtonDown(0)){
            float distance = difference.magnitude;
            Vector2 direction = difference / distance;
            direction.Normalize();
            fireBullet(direction, rotationZ);
        }
    }
    void fireBullet(Vector2 direction, float rotationZ){
        GameObject b = Instantiate(bulletPrefab) as GameObject;
        b.transform.position = bulletStart.transform.position;
        b.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
        b.GetComponent<Rigidbody2D>().velocity = direction * bulletSpeed;
    }
}

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community

Discussion

Browse Tutorials About