unity中制作滑动摇杆

准备素材

需要一个背景图片,和一个stick
在这里插入图片描述

实现原理

1.Stick跟随手指按下进行滑动,需要用到屏幕坐标转UI坐标。然后如果pos超过了圆的半径,需要将UI的Pos限制一下。

RectTransformUtility.ScreenPointToLocalPointInRectangle

2.Stick监听滑动和滑动结束事件,滑动结束回到原点。注意是Add New Event Type。而不是在一个Event Type里添加两个监听

3.最后可以将pos归一化处理得到一个Vector2值,返回给游戏处理移动

相关代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class JoyStick : MonoBehaviour {
    private Canvas cs;
    public Transform stick;
    //滑动的半径
    public float max_R = 80;

    private Vector2 touch_dir = Vector2.zero;
    public Vector2 dir {
        get {
            return this.touch_dir;
        }
    }

	// Use this for initialization
	void Awake () {
        this.cs = GameObject.Find("Canvas").GetComponent<Canvas>();
        this.stick.localPosition = Vector2.zero;
        this.touch_dir = Vector2.zero;
	}
	
	// Update is called once per frame
	void Update () {
        if (this.touch_dir.x == 0 && this.touch_dir.y == 0) {
            return;
        }
        Debug.Log(touch_dir);
        EventMgr.Instance.Emit("JoyStick", this.touch_dir);
	}

    public void OnStickDrag() {
        Vector2 pos = Vector2.zero;
        //屏幕坐标转UI坐标
        RectTransformUtility.ScreenPointToLocalPointInRectangle(this.transform as RectTransform, 
            Input.mousePosition, this.cs.worldCamera, out pos);
        //拖拽的半径
        float len = pos.magnitude;
        if (len <= 0) {
            this.touch_dir = Vector2.zero;
            return;
        }
        
        // 归一化, 
        this.touch_dir.x = pos.x / len; // cos(r)
        // this.touch_dir.y = pos.y / len; // (sinr) cos^2 + sin ^ 2 = 1;
        
        if (len >= this.max_R) { // this.max_R / len = x` / x = y` / y;
            pos.x = pos.x * this.max_R / len;
            pos.y = pos.y * this.max_R / len;
        }
        Debug.Log("OnStickDrag:"+pos);
        this.stick.localPosition = pos;
    }

    public void OnStickEndDrag() {
        this.stick.localPosition = Vector2.zero;
        this.touch_dir = Vector2.zero;
        EventMgr.Instance.Emit("JoyStick", this.touch_dir);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KindSuper_liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值