Hey everyone!
I’m learning the Input System currently and as is, I’m trying to make a top down 2D game. I am trying to get the basics to work on both gamepad and mouse/keyboard. I have it so the rotation is based on the mouse position for Keyboard/Mouse and based on the right stick for Gamepad. The issue is that when I switch to my gamepad, my player is still looking at my mouse. I want it so when using the gamepad, the mouse position is completely ignored. How should I do this?
Here are screenshots from my project and the code on my player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
PlayerInput playerInput;
[SerializeField] Camera main;
[SerializeField] float moveSpeed = 20f;
[SerializeField] float gamepadSensitivity = 250f;
[SerializeField] float mouseSensitivity = 400f;
Rigidbody2D rb;
InputAction moveAction;
InputAction lookAction;
private void Awake()
{
playerInput = GetComponent<PlayerInput>();
moveAction = playerInput.actions["Move"];
lookAction = playerInput.actions["Look"];
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
Move();
GamepadInput();
MouseInput();
}
void Move()
{
Vector3 move = moveAction.ReadValue<Vector2>() * moveSpeed * Time.deltaTime;
rb.transform.position += rb.transform.rotation * move;
}
void MouseInput()
{
Vector2 mouseScreenPosition = lookAction.ReadValue<Vector2>();
Vector3 mouseWorldPosition = main.ScreenToWorldPoint(mouseScreenPosition);
Vector3 targetDirection = mouseWorldPosition - rb.transform.position;
var step = mouseSensitivity * Time.deltaTime;
float mouseAngle = Mathf.Atan2(targetDirection.y, targetDirection.x) * Mathf.Rad2Deg - 90f;
rb.transform.rotation = Quaternion.RotateTowards(rb.transform.rotation, Quaternion.Euler(0f,0f,mouseAngle), step);
}
void GamepadInput()
{
Vector3 stickMoving = Vector3.zero;
Vector3 thumbstickValue = lookAction.ReadValue<Vector2>();
var step = gamepadSensitivity * Time.deltaTime;
if(thumbstickValue != Vector3.zero)
{
stickMoving = thumbstickValue;
float stickAngle = Mathf.Atan2(stickMoving.y, stickMoving.x) * Mathf.Rad2Deg - 90f;
rb.transform.rotation = Quaternion.RotateTowards(rb.transform.rotation, Quaternion.Euler(0f,0f,stickAngle), step);
}
}
}