Xử lý Input chuột và chạm màn hình
C# Code
using UnityEngine;
public class TouchAndMouseInput : MonoBehaviour
{
public float moveSpeed = 10f;
void Update()
{
Vector3 targetPosition = Vector3.zero;
bool hasInput = false;
// Xử lý Touch Input
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
{
targetPosition = Camera.main.ScreenToWorldPoint(touch.position);
hasInput = true;
}
}
// Xử lý Mouse Input
else if (Input.GetMouseButton(0)) // 0 là nút chuột trái
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
hasInput = true;
}
if (hasInput)
{
targetPosition.z = transform.position.z; // Giữ nguyên trục Z
transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
}
}
}Một script thống nhất để xử lý cả input từ chuột trên máy tính và chạm trên thiết bị di động để di chuyển một đối tượng.