Files
2026-03-04 10:03:45 +08:00

143 lines
3.0 KiB
C#

using UnityEngine;
namespace Artngame.GIPROXY
{
public class FirstPersonController : MonoBehaviour
{
public bool setResolution;
public int resX = 1280;
public int resY = 720;
public bool setFrameRateMobile;
public int frameRate = 60;
public float moveUpFactor;
[SerializeField]
private Transform cameraTransform;
[SerializeField]
private CharacterController characterController;
[SerializeField]
private float cameraSensitivity;
[SerializeField]
private float moveSpeed;
[SerializeField]
private float moveInputDeadZone;
private int leftFingerId;
private int rightFingerId;
private float halfScreenWidth;
private Vector2 lookInput;
private float cameraPitch;
private Vector2 moveTouchStartPosition;
private Vector2 moveInput;
private void Start()
{
if (setFrameRateMobile)
{
Application.targetFrameRate = frameRate;
}
if (setResolution)
{
Screen.SetResolution(resX, resY, fullscreen: true);
}
leftFingerId = -1;
rightFingerId = -1;
halfScreenWidth = Screen.width / 2;
moveInputDeadZone = Mathf.Pow((float)Screen.height / moveInputDeadZone, 2f);
}
private void Update()
{
GetTouchInput();
if (rightFingerId != -1)
{
LookAround();
}
if (leftFingerId != -1)
{
Move();
}
}
private void GetTouchInput()
{
for (int i = 0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
switch (touch.phase)
{
case TouchPhase.Began:
if (touch.position.x < halfScreenWidth && leftFingerId == -1)
{
leftFingerId = touch.fingerId;
moveTouchStartPosition = touch.position;
}
else if (touch.position.x > halfScreenWidth && rightFingerId == -1)
{
rightFingerId = touch.fingerId;
}
break;
case TouchPhase.Ended:
case TouchPhase.Canceled:
if (touch.fingerId == leftFingerId)
{
leftFingerId = -1;
}
else if (touch.fingerId == rightFingerId)
{
rightFingerId = -1;
}
break;
case TouchPhase.Moved:
if (touch.fingerId == rightFingerId)
{
lookInput = touch.deltaPosition * cameraSensitivity * Time.deltaTime;
}
else if (touch.fingerId == leftFingerId)
{
moveInput = touch.position - moveTouchStartPosition;
}
break;
case TouchPhase.Stationary:
if (touch.fingerId == rightFingerId)
{
lookInput = Vector2.zero;
}
break;
}
}
}
private void LookAround()
{
cameraPitch = Mathf.Clamp(cameraPitch - lookInput.y, -90f, 90f);
cameraTransform.localRotation = Quaternion.Euler(cameraPitch, 0f, 0f);
base.transform.Rotate(base.transform.up, lookInput.x);
}
private void Move()
{
if (!(moveInput.sqrMagnitude <= moveInputDeadZone))
{
Vector2 vector = moveInput.normalized * moveSpeed * Time.deltaTime;
characterController.Move(base.transform.right * vector.x + base.transform.forward * vector.y + base.transform.up * vector.y * moveUpFactor);
}
}
}
}