U3D游戏开发中摇杆的制作(UGUI版)

在PC端模拟摇杆,实现玩家通过控制摇杆让玩家移动,以下是完整代码:

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

public class Move : MonoBehaviour
{
    //设置关联摇杆
    public EventTrigger controller;
    //获取正方体的位置信息
    public Transform cube;
    //设置正方体的移动速度
    public float moveSpeed = 5f;
    //设置当前移动方向
    private Vector3 moveDir;
    //坦克是否移动
    private bool isMoving;
    public float roundSpeed = 20f;
    //监听事件

    // Start is called before the first frame update
    void Start()
    {
        EventTrigger.Entry entry = new EventTrigger.Entry();
        //声明事件类型
        entry.eventID = EventTriggerType.Drag;
        //监听函数关联
        entry.callback.AddListener((data) =>
        {
            //改变对象位置
           PointerEventData eventData= data as PointerEventData;
            controller.transform.localPosition += new Vector3(eventData.delta.x,eventData.delta.y,0);
            //判断极限
            if(controller.transform.localPosition.magnitude>130)
            {
                controller.transform.localPosition = controller.transform.localPosition.normalized * 130;
            }
            //拖动时让玩家移动
            MoveTo(controller.transform.localPosition.normalized);
        });
        controller.triggers.Add(entry);

        EventTrigger.Entry entry1=new EventTrigger.Entry();
        entry1.eventID=EventTriggerType.EndDrag;
        entry1.callback.AddListener((data) =>
        {
            //回到原点
            controller.transform.localPosition = Vector3.zero;
            //玩家停止移动
            StopMoving();
        });
        controller.triggers.Add(entry1);
    }

    // Update is called once per frame
    void Update()
    {
        if(isMoving)
        {
            //位移
            this.transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);
            //旋转
            this.transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.LookRotation(moveDir), roundSpeed * Time.deltaTime);
        }
    }
    //控制移动
    public void MoveTo(Vector3 dir)
    {
        moveDir.x = dir.x;
        moveDir.z = dir.y;
        isMoving= true;
    }
    //停止移动
    public void StopMoving()
    {
        isMoving= false;
    }
}

希望我的笔记对你有所帮助,喜欢就点赞收藏吧!

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Nicole Potter

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

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

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

打赏作者

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

抵扣说明:

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

余额充值