unity 摇杆控件

如果有人看不懂下面的代码的使用方法,这里准备了一个网盘项目文件压缩包,用unity2017及以上版本打开即可

网址:https://pan.baidu.com/s/1Pu2qgNV7CqCjF613EwO3zg

using UnityEngine;
public class Control : MonoBehaviour {
    public Texture Point, Ring;
    public static float x, y;
    Vector2 Posi, Pos0, Pos00, Pos_;
    float RingW, RingH, PointW, PointH;
    bool Drag;

    void Start() {
        Pos00 = Pos0 = Posi = new Vector2(300, 800);
        RingW = RingH = 400;
        PointW = PointH = 150;
        Drag = false;
        x = y = 0;
    }

    void Update() {
    }

    void OnGUI() {
        if (Event.current.type == EventType.mouseDown) {

            //是否需要移动控件
            Vector2 Posq = Event.current.mousePosition;
            float vz0;
            vz0 = (Posq.x - Pos0.x) * (Posq.x - Pos0.x) + (Posq.y - Pos0.y) * (Posq.y - Pos0.y);
            vz0 = Mathf.Sqrt(vz0);
            if (vz0 < RingW / 2) {
                Pos0 = Event.current.mousePosition;
                Drag = true;
            }
        }

        //抬起手指,归位
        if (Event.current.type == EventType.mouseUp) {
            Drag = false;
            Pos0 = Pos00;
        }

        //拖拽
        x = 0;
        y = 0;
        float vx = 0, vy = 0, vz;
        
        Pos_ = Event.current.mousePosition;
        vz = (Pos_.x - Pos0.x) * (Pos_.x - Pos0.x) + (Pos_.y - Pos0.y) * (Pos_.y - Pos0.y);
        vz = Mathf.Sqrt(vz);
        if (Drag) Posi = Pos_;
        else Posi = Pos0;

        if (vz > RingW / 2) {
            vx = (Posi.x - Pos0.x) / vz * RingW / 2 + Pos0.x;
            vy = (Posi.y - Pos0.y) / vz * RingH / 2 + Pos0.y;
            Posi = new Vector2(vx, vy);
        }

        GUI.DrawTexture(new Rect(Posi.x - PointW / 2, Posi.y - PointH / 2, PointW, PointH), Point);
        GUI.DrawTexture(new Rect(Pos0.x - RingW / 2, Pos0.y - RingH / 2, RingW, RingH), Ring);

        //外部速度接口
        if (Drag) Posi = Event.current.mousePosition;
        else Posi = Pos0;
        vz = (Posi.x - Pos0.x) * (Posi.x - Pos0.x) + (Posi.y - Pos0.y) * (Posi.y - Pos0.y);
        vz = Mathf.Sqrt(vz);
        x = Mathf.Abs(Posi.x - Pos0.x) / (RingW / 2) * (Posi.x - Pos0.x) / vz;
        y = -Mathf.Abs(Posi.y - Pos0.y) / (RingH / 2) * (Posi.y - Pos0.y) / vz;
        if (vz == 0) x = y = 0;
        if (vz > RingW / 2) {
            x= (Posi.x - Pos0.x) / vz; 
            y= -(Posi.y - Pos0.y) / vz;
        }
        //其它脚本获得速度方向时,可写作:
        //gameObject.transform.Translate(Time.deltaTime * Speed * Control.x, Time.deltaTime * Speed * Control.y, 0);
    }
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值