Skip to content

Instantly share code, notes, and snippets.

@saturngamesss
Created July 9, 2020 17:31
Show Gist options
  • Save saturngamesss/91da6e728790a1f8f7eeb0235bba830a to your computer and use it in GitHub Desktop.
Save saturngamesss/91da6e728790a1f8f7eeb0235bba830a to your computer and use it in GitHub Desktop.
Simple 2D shooting to mouse direction code for Unity Engine.
//************** REAL GAMES STUDIO ***************
//************************************************
//realgamesss.weebly.com
//gamejolt.com/@Real_Game
//realgamesss.newgrounds.com/
//real-games.itch.io/
//youtube.com/channel/UC_Adg-mo-IPg6uLacuQCZCQ
//************************************************
using UnityEngine;
public class shooting : MonoBehaviour
{
public GameObject bullet;
public Transform firePoint;
public float bulletSpeed = 50;
Vector2 lookDirection;
float lookAngle;
void Update()
{
lookDirection = Camera.main.ScreenToWorldPoint(Input.mousePosition);
lookAngle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg;
firePoint.rotation = Quaternion.Euler(0, 0, lookAngle);
if (Input.GetMouseButtonDown(0))
{
GameObject bulletClone = Instantiate(bullet);
bulletClone.transform.position = firePoint.position;
bulletClone.transform.rotation = Quaternion.Euler(0, 0, lookAngle);
bulletClone.GetComponent<Rigidbody2D>().velocity = firePoint.right * bulletSpeed;
}
}
}
@Cratior
Copy link

Cratior commented Nov 11, 2022

works great.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment