【发布时间】:2017-12-05 04:59:15
【问题描述】:
我在 Unity 中使用操纵杆移动相机时遇到问题。我把这段代码写到我的操纵杆上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler {
private Image bgImg;
private Image joystickImg;
private Vector2 pos;
private void Start()
{
bgImg = GetComponent<Image>();
joystickImg = transform.GetChild(0).GetComponent<Image>();
}
public virtual void OnDrag(PointerEventData ped)
{
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
{
pos.x = (pos.x * 2 + 1) / bgImg.rectTransform.sizeDelta.x;
pos.y = (pos.y * 2 - 1) / bgImg.rectTransform.sizeDelta.y;
pos = (pos.magnitude > 1.0f) ? pos.normalized : pos;
// Move Joystrick IMG
joystickImg.rectTransform.anchoredPosition = new Vector2(pos.x * (bgImg.rectTransform.sizeDelta.x / 3), pos.y * (bgImg.rectTransform.sizeDelta.y / 3));
}
}
public virtual void OnPointerDown(PointerEventData ped)
{
OnDrag(ped);
}
public virtual void OnPointerUp(PointerEventData ped)
{
pos = Vector2.zero;
joystickImg.rectTransform.anchoredPosition = Vector2.zero;
}
public float Horizontal()
{
if (pos.x != 0)
{
return pos.x;
}
else
{
return Input.GetAxis("Horizontal");
}
}
public float Vertical()
{
if (pos.y != 0)
{
return pos.y;
}
else
{
return Input.GetAxis("Vertical");
}
}
}
这段代码运行良好,动态返回 Vector2(x,y)。所以,现在我想使用这个操纵杆和这些坐标来移动相机(改变位置 X,Y)。你知道怎么做吗?每个人都展示了如何移动立方体或球体,而无处可移如何平移相机......
【问题讨论】: