_xiaofang/xiaofang/Assets/Script/hylScripts/JoystickController.cs

70 lines
2.0 KiB
C#
Raw Normal View History

2024-12-19 11:54:47 +08:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class JoystickController : MonoBehaviour, IDragHandler, IEndDragHandler
{
public bool isDrag = false;
public RectTransform joystickBackground; // ҡ<>˱<EFBFBD><CBB1><EFBFBD>
public RectTransform joystick; // ҡ<><D2A1>
public Camera playerCamera; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
public float rotationSpeed = 5f; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ת<EFBFBD>ٶ<EFBFBD>
private Vector2 joystickInput = Vector2.zero;
void Start()
{
// <20><>ʼ<EFBFBD><CABC>ҡ<EFBFBD>˵<EFBFBD>λ<EFBFBD><CEBB>
joystick.anchoredPosition = Vector2.zero;
}
// ÿ֡<C3BF><D6A1><EFBFBD><EFBFBD>ҡ<EFBFBD>˵<EFBFBD><CBB5><EFBFBD><EFBFBD><EFBFBD>
void Update()
{
if (joystickInput.magnitude > 0)
{
// <20><><EFBFBD><EFBFBD>ҡ<EFBFBD>˵<EFBFBD><CBB5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ת
float horizontal = joystickInput.x;
float vertical = joystickInput.y;
// ˮƽ<CBAE><C6BD>ת
playerCamera.transform.Rotate(Vector3.up, horizontal * rotationSpeed * Time.deltaTime);
// <20><>ֱ<EFBFBD><D6B1>ת
playerCamera.transform.Rotate(Vector3.left, vertical * rotationSpeed * Time.deltaTime);
}
}
// ҡ<><D2A1><EFBFBD>϶<EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>ҡ<EFBFBD><D2A1>λ<EFBFBD>ú<EFBFBD><C3BA><EFBFBD><EFBFBD><EFBFBD>
public void OnDrag(PointerEventData eventData)
{
isDrag = true;
// <20><><EFBFBD><EFBFBD>ҡ<EFBFBD>˵<EFBFBD>λ<EFBFBD><CEBB>
joystick.anchoredPosition = joystickInput;
Vector2 localPoint;
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>λ<EFBFBD>ô<EFBFBD><C3B4><EFBFBD>Ļ<EFBFBD><C4BB><EFBFBD><EFBFBD>ת<EFBFBD><D7AA>ΪUI<55><49><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
RectTransformUtility.ScreenPointToLocalPointInRectangle(joystickBackground, eventData.position, eventData.pressEventCamera, out localPoint);
// <20><><EFBFBD><EFBFBD>ҡ<EFBFBD>˵<EFBFBD><CBB5><EFBFBD><EFBFBD><EFBFBD><EBB7BD>
joystickInput = localPoint.normalized;
// <20><><EFBFBD><EFBFBD>ҡ<EFBFBD>˵<EFBFBD><CBB5>ƶ<EFBFBD><C6B6><EFBFBD>Χ<EFBFBD><CEA7>ȷ<EFBFBD><C8B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E1B3AC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ı߽<C4B1>
if (localPoint.magnitude > joystickBackground.sizeDelta.x / 2)
{
joystickInput = localPoint.normalized * (joystickBackground.sizeDelta.x / 2);
}
}
// ҡ<><D2A1><EFBFBD>ɿ<EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>ҡ<EFBFBD><D2A1>λ<EFBFBD><CEBB>
public void OnEndDrag(PointerEventData eventData)
{
isDrag = false;
joystick.anchoredPosition = Vector2.zero;
joystickInput = Vector2.zero;
}
}