100 lines
3.1 KiB
C#
100 lines
3.1 KiB
C#
using BrewMonster;
|
|
using System.Collections;
|
|
using Unity.Cinemachine;
|
|
using UnityEngine;
|
|
|
|
public class CinemachineTouchOrbit : MonoSingleton<CinemachineTouchOrbit>
|
|
{
|
|
public CinemachineCamera cineCam;
|
|
public Transform player;
|
|
|
|
[Header("Settings")]
|
|
public float inputSpeed = 0.2f;
|
|
public float clampPitchMin = -30f;
|
|
public float clampPitchMax = 60f;
|
|
public float distance = 5f; // khoảng cách camera phía sau
|
|
|
|
float yawOffset = 0f; // phần xoay do input
|
|
float pitchOffset = 0f;
|
|
|
|
Vector2 lastPointerPos;
|
|
bool isDragging = false;
|
|
|
|
void LateUpdate()
|
|
{
|
|
if (player == null || cineCam == null) return;
|
|
|
|
// 1. Lấy hướng player (yaw)
|
|
float playerYaw = player.eulerAngles.y;
|
|
|
|
// 2. Lấy input delta (chuột / touch) để xoay camera thêm
|
|
Vector2 delta = GetInputDelta();
|
|
yawOffset += delta.x * inputSpeed;
|
|
pitchOffset -= delta.y * inputSpeed;
|
|
pitchOffset = Mathf.Clamp(pitchOffset, clampPitchMin, clampPitchMax);
|
|
|
|
// 3. Tính rotation cuối = playerYaw + yawOffset
|
|
float finalYaw = playerYaw + yawOffset;
|
|
float finalPitch = pitchOffset;
|
|
|
|
// 4. Cập nhật vị trí + hướng camera
|
|
Quaternion rot = Quaternion.Euler(finalPitch, finalYaw, 0f);
|
|
Vector3 offset = rot * new Vector3(0, 0, -distance);
|
|
cineCam.transform.position = player.position + offset;
|
|
cineCam.transform.rotation = rot;
|
|
}
|
|
|
|
Vector2 GetInputDelta()
|
|
{
|
|
// Nếu test trên editor / PC
|
|
#if UNITY_EDITOR || UNITY_STANDALONE
|
|
if (Input.GetMouseButtonDown(0))
|
|
{
|
|
lastPointerPos = Input.mousePosition;
|
|
isDragging = true;
|
|
}
|
|
if (Input.GetMouseButtonUp(0))
|
|
{
|
|
isDragging = false;
|
|
}
|
|
if (isDragging && Input.GetMouseButton(0))
|
|
{
|
|
Vector2 cur = Input.mousePosition;
|
|
Vector2 delta = cur - lastPointerPos;
|
|
lastPointerPos = cur;
|
|
// Nếu chạm vùng joystick thì ignore
|
|
return delta;
|
|
}
|
|
return Vector2.zero;
|
|
#else
|
|
// Mobile: xử lý touch tương tự code bạn đã có
|
|
// foreach (Touch t in Input.touches)
|
|
// {
|
|
// if (t.phase == TouchPhase.Began)
|
|
// {
|
|
// lastPointerPos = t.position;
|
|
// isDragging = true;
|
|
// }
|
|
// else if (t.phase == TouchPhase.Moved && isDragging)
|
|
// {
|
|
// Vector2 cur = t.position;
|
|
// Vector2 delta = cur - lastPointerPos;
|
|
// lastPointerPos = cur;
|
|
// if (RectTransformUtility.RectangleContainsScreenPoint(joystickArea, cur))
|
|
// return Vector2.zero;
|
|
// return delta;
|
|
// }
|
|
// else if (t.phase == TouchPhase.Ended || t.phase == TouchPhase.Canceled)
|
|
// {
|
|
// isDragging = false;
|
|
// }
|
|
// }
|
|
return Vector2.zero;
|
|
#endif
|
|
}
|
|
public void SetOrbitTarget(Transform target)
|
|
{
|
|
player = target;
|
|
}
|
|
}
|