代码的虚拟轴

在这里插入图片描述

虚拟轴只是俩张图片,下边的代码是挂在中间的小图片上的,不用插件:

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是物体移动速度,可以自己调,以上的就是全部代码,要用的自己往项目里添加吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值