【unity2D】实现摇杆移动人物

之前做过一次但是忘了,这次费了老大劲,发誓一定长记性!

1. JoyStick摇杆在canvas画布中的绑定

  • 在canvas中创建一个image命名为摇杆背景
  • 再在这个背景下创建一个image命名为摇杆
  • 创建JoyStick代码
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Joystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
    private Image joystickBg;
    private Image joystick;
    private Vector3 inputVector;

    void Start()
    {
        joystickBg = GetComponent<Image>();
        joystick = transform.GetChild(0).GetComponent<Image>();
    }

    public virtual void OnDrag(PointerEventData eventData)
    {
        Vector2 pos;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(joystickBg.rectTransform, eventData.position, eventData.pressEventCamera, out pos))
        {
            pos.x = (pos.x / joystickBg.rectTransform.sizeDelta.x);
            pos.y = (pos.y / joystickBg.rectTransform.sizeDelta.y);

            inputVector = new Vector3(pos.x * 2 - 1, pos.y * 2 - 1, 0);
            inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;

            joystick.rectTransform.anchoredPosition = new Vector3(inputVector.x * (joystickBg.rectTransform.sizeDelta.x / 2), inputVector.y * (joystickBg.rectTransform.sizeDelta.y / 2));
        }
    }

    public virtual void OnPointerDown(PointerEventData eventData)
    {
        OnDrag(eventData);
    }

    public virtual void OnPointerUp(PointerEventData eventData)
    {
        inputVector = Vector3.zero;
        joystick.rectTransform.anchoredPosition = Vector3.zero;
    }

    public float Horizontal()
    {
        return (-1)*inputVector.x;
    }

    public float Vertical()
    {
        return inputVector.y;
    }
}

  • 将JoyStick代码绑定在摇杆背景上,摇杆将可以围绕摇杆背景移动

2. 将摇杆绑定在角色身上实现移动

  • 创建Player代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public float moveSpeed = 5f;
    public Joystick joystick; // 参考到摇杆脚本

    void Update()
    {
        Vector3 moveVector = new Vector3(joystick.Horizontal(), joystick.Vertical(), 0f);
        transform.Translate(moveVector * moveSpeed * Time.deltaTime);
    }
}
  • 将代码添加到角色身上,并将摇杆背景拖拽到右边的脚本上

这样就好了!

后续添加动画什么的即可自行设置。

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值