zoukankan      html  css  js  c++  java
  • unity使用UGUI创建摇杆

    1.现在unity做一个项目,各种插件各种包,于是项目资源就无限变大了,其实一些简单的功能可以自己写,这里就是试着使用UGUI编写一个摇杆功能

    2.脚本如下:

    [c#] view plain copy
     
    1. using UnityEngine;  
    2. using UnityEngine.UI;  
    3. using UnityEngine.EventSystems;  
    4. using System.Collections;  
    5.   
    6. public class UGUIJoystick : MonoBehaviour,IDragHandler{  
    7.   
    8.     public RectTransform joystickImage;  
    9.     public Vector3 startPos;  
    10.     public int maxDis = 70;  
    11.     public float speed = 5;  
    12.   
    13.     // Use this for initialization  
    14.     void Start () {  
    15.         startPos = joystickImage.position;  
    16.     }  
    17.       
    18.     // Update is called once per frame  
    19.     void Update () {  
    20.   
    21.         if (Application.platform == RuntimePlatform.Android)  
    22.         {  
    23.             if (Input.touchCount <= 0)  
    24.             {  
    25.                 if (Vector3.Distance(joystickImage.position, startPos) > 0.01f)  
    26.                 {  
    27.                     joystickImage.position = joystickImage.position - (joystickImage.position - startPos).normalized * speed;  
    28.                 }  
    29.             }  
    30.         }  
    31.         else  
    32.         {  
    33.             if (!Input.GetMouseButton(0))  
    34.             {  
    35.                 if (Vector3.Distance(joystickImage.position, startPos) > 0.01f)  
    36.                 {  
    37.                     joystickImage.position = joystickImage.position - (joystickImage.position - startPos).normalized * speed;  
    38.                 }  
    39.             }  
    40.         }  
    41.   
    42.     }  
    43.   
    44.    public void OnDrag(PointerEventData eventData)  
    45.     {  
    46.         Vector3 wordPos;  
    47.         //将UGUI的坐标转为世界坐标  
    48.         if (RectTransformUtility.ScreenPointToWorldPointInRectangle(joystickImage, eventData.position, eventData.pressEventCamera, out wordPos))  
    49.             joystickImage.position = wordPos;  
    50.   
    51.         Vector3 dir = (joystickImage.position - startPos).normalized;  
    52.         if (Vector3.Distance(joystickImage.position, startPos) >= maxDis)  
    53.         {  
    54.             joystickImage.position = startPos + dir * maxDis;  
    55.         }  
    56.     }  
    57. }  

    3.这里除了一个简单的接口实现,就是坐标的转换,让摇杆一直跟着手指移动,这里就需要一个函数RectTransformUtility.ScreenPointToWorldPointInRectangle

    4.将这个脚本绑定在摇杆用于移动的图片上,效果如下:

    5.摇杆常用移动端,但是我并未在移动端测试

     
     
  • 相关阅读:
    [ActionSprit 3.0] FMS直播
    Selenium学习之==>Css Selector使用方法
    Selenium学习之==>Xpath使用方法
    Selenium学习之==>WebDriver驱动对照表
    Selenium学习之==>Selenium介绍
    HTML学习之==>JS
    HTML学习之==>DOM操作
    HTML学习之==>CSS
    HTML学习之==>HTML标签
    Python学习之==>线程&&进程
  • 原文地址:https://www.cnblogs.com/feiqianlove/p/6825790.html
Copyright © 2011-2022 走看看