Files
AnimalDictionary/Assets/Script/Animal.cs
T
2026-05-07 16:37:02 +09:00

59 lines
1.8 KiB
C#

using UnityEngine;
using UnityEngine.InputSystem;
public class Animal : MonoBehaviour
{
public LayerMask animalLayer;
public AudioSource audioSource;
public AudioClip crySound;
[SerializeField] float rotateSpeed = 0.3f;
[SerializeField] float followSpeed = 5f;
[SerializeField] float followDistance = 1.5f;
bool isDragging = false;
Vector2 lastTouchPos;
void Update()
{
if (Touchscreen.current == null) return;
var touch = Touchscreen.current.primaryTouch;
// 터치 시작
if (touch.press.wasPressedThisFrame)
{
Vector2 touchPos = touch.position.ReadValue();
Ray ray = Camera.main.ScreenPointToRay(touchPos);
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, animalLayer))
{
if (hit.transform.IsChildOf(transform))
{
isDragging = true;
lastTouchPos = touchPos;
if (crySound != null && !audioSource.isPlaying)
audioSource.PlayOneShot(crySound);
}
}
}
// 드래그 중 좌우 회전
if (touch.press.isPressed && isDragging)
{
Vector2 currentPos = touch.position.ReadValue();
float deltaX = currentPos.x - lastTouchPos.x;
transform.Rotate(Vector3.up, -deltaX * rotateSpeed, Space.World);
lastTouchPos = currentPos;
}
// 터치 종료
if (touch.press.wasReleasedThisFrame)
isDragging = false;
// 항상 카메라 앞 중앙에 부드럽게 위치
Vector3 targetPos = Camera.main.transform.position + Camera.main.transform.forward * followDistance;
transform.position = Vector3.Lerp(transform.position, targetPos, followSpeed * Time.deltaTime);
}
}