手写摇杆(简单版)

角色移动代码

 

锚点必须设置正确否则会偏移

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Rocker : MonoBehaviour,IEndDragHandler,IDragHandler
{
public static Vector2 offset;//角色需要用的位置
public RectTransform bar;//摇杆
public RectTransform rocker;//摇杆底座
public float r;
public void OnDrag(PointerEventData eventData)
{
Vector2 pos = eventData.position - rocker.anchoredPosition;//求摇杆相对遥感底座的位置
Debug.Log(eventData.position);
//pos 是当前位置 r是限制最大的范围
bar.anchoredPosition = Vector2.ClampMagnitude(pos,r);//防止拉出摇杆底座
offset = bar.anchoredPosition / r;//求遥感与遥感底座的比值 比值-1 到 1;
}

public void OnEndDrag(PointerEventData eventData)
{
bar.anchoredPosition = Vector2.zero;//遥感位置清0
offset = Vector2.zero;//清零 不然角色会一直移动


}

// Start is called before the first frame update
void Start()
{
rocker = GetComponent<RectTransform>();//获得矩形类
r = rocker.rect.width < rocker.rect.height ? rocker.rect.width / 2 : rocker.rect.height / 2;//根据矩形宽高选择半径
}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值