zoukankan      html  css  js  c++  java
  • 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 即可,对应水平和垂直方向。

  • 相关阅读:
    Linux Ubuntu系统的安装||grub启动字符界面
    linux 第一个qt程序 以及 linux qt cannotfind lgL的解决
    linux ftp 文件传输的搭建 以qt上传为例
    linux gcc 安装和第一个hello world脚本
    python bug debug
    python 元组的概念以及 math 模块
    移动端调试
    移动终端学习2:触屏原生js事件及重力感应
    input file 类型为excel表格
    gulp构建工具的安装
  • 原文地址:https://www.cnblogs.com/duyushuang/p/4457691.html
Copyright © 2011-2022 走看看