虚拟轴只是俩张图片,下边的代码是挂在中间的小图片上的,不用插件:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class VirtualDemo : MonoBehaviour,IDragHandler,IEndDragHandler {
Vector3 v3;
RectTransform rect;
Vector3 world;
Vector2 screen;
Vector2 middle;
float radius;
public Vector3 movev3;
public void OnDrag(PointerEventData eventData)
{
middle = eventData.position - screen;
movev3 = middle.normalized.y * Vector3.up;
movev3 += middle.normalized.x * Vector3.right;
if(middle .magnitude >radius )
{
middle = middle.normalized * radius;
}
rect.anchoredPosition = middle;
}
public void OnEndDrag(PointerEventData eventData)
{
movev3 = Vector3.zero;
transform.position = v3;
}
void Start () {
rect = GetComponent<RectTransform>();
v3 = transform.position;
radius = transform.parent.GetComponent<RectTransform>().rect.width / 2;
world = rect.position;
screen = RectTransformUtility.WorldToScreenPoint(null, world);
}
public Vector3 gethandl()
{
return movev3;
}
}
现在是2D的把y轴v3乘以的换成forward,就是3D的,下边的挂在要移动的物体上的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VirtualMove : MonoBehaviour {
public GameObject obj;
VirtualDemo virtualDemo;
void Start () {
virtualDemo = obj.GetComponent<VirtualDemo>();
}
void Update () {
transform.Translate(virtualDemo.movev3 * Time.deltaTime*100);
}
}
最后的100是物体移动速度,可以自己调,以上的就是全部代码,要用的自己往项目里添加吧