How’s it going - I’m making a 2D game where the player character rotates to face the mouse position. I’ve gotten it working using the new input system by converting the player mousePosition into a Vector3 & then finding the angle of that.
I also have a camera that follows the player as they move through gamespace - my issue is that once the character moves outside of the initial screen, the final angle gets increasingly wonky. Is there away I can account for that in my calculations? Thank you.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public PlayerInputActions playerInput;
public Rigidbody2D rb;
public playerWeapon weapon;
Vector2 moveDirection;
Vector2 movePosition;
[SerializeField] public float speed = 5f;
// Start is called before the first frame update
private void Awake()
{
playerInput = new PlayerInputActions();
rb = GetComponent<Rigidbody2D>();
}
private void OnEnable()
{
playerInput.Enable();
}
private void OnDisable()
{
playerInput.Disable();
}
void Update()
{
Vector2 moveInput = playerInput.Movement.Move.ReadValue<Vector2>();
rb.velocity = moveInput * speed;
playerInput.Movement.Attack.ReadValue<float>();
if (playerInput.Movement.Attack.triggered)
{
Debug.Log ("Attack");
weapon.fire();
}
}
// Update is called once per frame
private void FixedUpdate()
{
Vector3 mousePos = playerInput.Movement.mousePosition.ReadValue<Vector2>();
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mousePos);
Vector3 aimDirection = worldPosition;
mousePos.z = 0;
float aimAngle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg - 90f;
rb.rotation = aimAngle;
}
}