Ive been trying to make it so that the players arm points a gun towards where the mouse is (basically just 2D aiming) but for some reason the angles are always consistent. For example it would line up with the mouse while facing up and down but when facing forward it would be completely off.
using UnityEngine;
using static UnityEditor.Experimental.GraphView.GraphView;
public class PlayerAim : MonoBehaviour
{
public GameObject arm, gun, shootPoint;
public GameObject bullet;
float orientation;
PlayerController player;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
player = GetComponent<PlayerController>();
orientation = transform.localScale.x;
}
// Update is called once per frame
void Update()
{
Aim();
}
void Aim()
{
Vector3 aimDir = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position).normalized;
float angle = Mathf.Atan2(aimDir.y, aimDir.x) * Mathf.Rad2Deg;
if (player.horiz == 0)
{
if (Camera.main.ScreenToWorldPoint(Input.mousePosition).x < transform.position.x)
{
player.facingLeft = true;
transform.localScale = new Vector3(-orientation, transform.localScale.y, transform.localScale.z);
}
else
{
player.facingLeft = false;
transform.localScale = new Vector3(orientation, transform.localScale.y, transform.localScale.z);
}
}
if (player.facingLeft)
{
arm.transform.rotation = Quaternion.Euler(0, 0, angle + 190);
}
else
{
arm.transform.rotation = Quaternion.Euler(0, 0, angle - 10);
}
if (Input.GetMouseButtonDown(0))
{
Shoot();
}
}
void Shoot()
{
gun.GetComponent<Animator>().SetTrigger("Shoot");
Instantiate(bullet, shootPoint.transform.position, Quaternion.Euler(0, 0, shootPoint.transform.rotation.eulerAngles.z));
}
}