• ugui自制摇杆。


    珍爱生命,远离插件。

    以上8个字,好好理解。

    反正我是这么觉得。

    我说的是unity,不是魔兽世界。

    总有一天,我会一句一句写出属于自己的东西。

    可以开始主题了。

           

    如图所示,建立一个画布,添加两个image即可(注意父子关系,父亲为摇杆外面的那个圆圈),然后调整位置到左下角,调节锚点,选左下角那个。

    接下来编辑脚本

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

    public class Joystick : MonoBehaviour, IBeginDragHandler, IDragHandler ,IEndDragHandler{

        public Vector3 normalCenter;
        public static float joystickH;
        public static float joystickV;

        private bool isDrag;
        private Vector3 startPos;
        private Vector3 dragPos;


        void Awake()
        {
            isDrag = false;
            startPos = transform.localPosition;
        }

        void Update()
        {
            if(isDrag)
            {
                float distance = Vector3.Distance(dragPos, normalCenter);
                Vector3 dirNormal = dragPos - normalCenter;
                if(distance > 45)
                {
                    transform.localPosition = dirNormal.normalized * 50;
                }
                else
                {
                    transform.localPosition = dirNormal;
                }
                joystickH = dirNormal.x / 1000;
                joystickV = dirNormal.y / 1000;
            }
            else
            {
                transform.localPosition = startPos;
                joystickH = 0;
                joystickV = 0;
            }
        }

        public void OnBeginDrag(PointerEventData eventData)
        {
            isDrag = true;
        }

        public void OnDrag(PointerEventData eventData)
        {
            dragPos = eventData.position;
        }

        public void OnEndDrag(PointerEventData eventData)
        {
            isDrag = false;
        }
    }

    OK,回到unity运行程序,是不是可以动了呢。

    让别的物体动的话,只需在控制移动的脚本里调用 joystickH  joystickV 即可,对应水平和垂直方向。

  • 相关阅读:
    Java设计模式(学习整理)---工厂模式
    Java Swing 使用总结(转载)
    Java-生成验证码图片(自定义内容,尺寸,路径)
    二维码(带有图片)的生成
    J2se中的声音---AudioPlayer
    文件的读取和写入(指定路径)
    ASP.NET:使用Flurl制作可复用的分页组件
    ASP.NET:Forms身份验证和基于Role的权限验证
    ASP.NET:MVC模板化机制
    ASP.NET:MVC中文件上传与地址变化处理
  • 原文地址:https://www.cnblogs.com/duyushuang/p/4457691.html
Copyright © 2020-2023  润新知