I am trying to make a shooting system and it isn’t working correctly. I try to spawn my bullet and rotate it in the direction I am aiming, but it isn’t working. I don’t understand Quaternions so i tried using Quaternion.LookRotation or Quaternion.EulerAngles but they both rotate the wrong axis and it makes it so the sprite is invisible. Also this is for a topdown shooter…
using UnityEngine;
public class Player : MonoBehaviour
{
public float moveSpeed;
public GameObject bulletPrefab;
public Camera mainCam;
private Rigidbody2D _rigidbody;
private Vector2 _moveDir;
private Vector2 _mousePos;
private bool _hasShot;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
private void Update()
{
GatherInput();
Shoot();
}
private void FixedUpdate()
{
Move();
}
private void GatherInput()
{
_moveDir.x = Input.GetAxis("Horizontal");
_moveDir.y = Input.GetAxis("Vertical");
_hasShot = Input.GetButtonDown("Fire1");
_mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
}
private void Move()
{
_rigidbody.velocity = _moveDir * (moveSpeed * Time.fixedDeltaTime);
}
private void Shoot()
{
if (_hasShot)
{
Vector2 aimDir = (_mousePos - (Vector2)transform.position).normalized;
Instantiate(bulletPrefab, transform.position, Quaternion.LookRotation(aimDir));
_hasShot = false;
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawSphere(_mousePos, 1f);
Gizmos.DrawLine(transform.position, (Vector2)transform.position + (_mousePos - (Vector2)transform.position).normalized);
}
}