Im trying to make a TPS on mobile. Now i want implement a basic control system where on the left side of screen the player is able to move via joystick and on the right side of the screen the player is able to look around using swipe. Now the problem I faced is that the player isnt able to move and rotate at same time. It will only either move or rotate cant do simunltaniously.
Here is the code for the look. For the move i used a virtual joystick with the On Screen Stick script provided by the unity.
using UnityEngine;
using UnityEngine.InputSystem;
public class TouchControls : MonoBehaviour
{
[SerializeField] private InputActionAsset inputAction;
public GameObject CameraLook;
public GameObject Player;
private InputAction LookAction;
private Vector2 lookInput;
private Vector2 CameraRotation;
[SerializeField] public float PitchSensitivity;
[SerializeField] public float YawSensitivity;
[SerializeField] public float Min;
[SerializeField] public float Max;
private float VerticalRotation;
private int rightFingerId;
private float halfScreenWidth;
void Awake()
{
LookAction = inputAction.FindActionMap("Player").FindAction("Look");
}
private void OnEnable()
{
LookAction.Enable();
}
private void OnDisable()
{
LookAction.Disable();
}
void Start()
{
// id = -1 means the finger is not being tracked
rightFingerId = -1;
// only calculate once
halfScreenWidth = Screen.width / 2;
}
// Update is called once per frame
void Update()
{
GetTouchInput();
if (rightFingerId != -1)
{
// Ony look around if the right finger is being tracked
LookAround();
}
}
void LookAround()
{
float PlayerRotation = lookInput.x * YawSensitivity * Time.deltaTime;
Player.transform.Rotate(0, PlayerRotation, 0);
VerticalRotation = Mathf.Clamp(VerticalRotation, Min, Max);
CameraLook.transform.localRotation = Quaternion.Euler(VerticalRotation, 0, 0);
}
void GetTouchInput()
{
// Iterate through all the detected touches
for (int i = 0; i < Input.touchCount; i++)
{
Touch t = Input.GetTouch(i);
// Check each touch's phase
switch (t.phase)
{
case UnityEngine.TouchPhase.Began:
if (t.position.x > halfScreenWidth && rightFingerId == -1)
{
// Start tracking the rightfinger if it was not previously being tracked
rightFingerId = t.fingerId;
}
break;
case UnityEngine.TouchPhase.Ended:
case UnityEngine.TouchPhase.Canceled:
if (t.fingerId == rightFingerId)
{
// Stop tracking the right finger
rightFingerId = -1;
Debug.Log("Stopped tracking right finger");
}
break;
case UnityEngine.TouchPhase.Moved:
// Get input for looking around
if (t.fingerId == rightFingerId)
{
lookInput = LookAction.ReadValue<Vector2>();
VerticalRotation -= lookInput.y * PitchSensitivity * Time.deltaTime;
}
break;
case UnityEngine.TouchPhase.Stationary:
// Set the look input to zero if the finger is still
if (t.fingerId == rightFingerId)
{
VerticalRotation -= 0;
}
break;