码迷,mamicode.com
首页 > 其他好文 > 详细

UGUI实现摇杆

时间:2015-06-29 21:59:08      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

效果图

技术分享

 

 

立方体好比角色。可以利用右下角的摇杆控制角色移动

看看结构图

技术分享

Image1:是外面圆圈

Image2:是蓝色圈

创建JoyStickScript.cs代码挂载在Image2上。这里没有实现控制立方体移动。有待改进

 1 using UnityEngine;
 2 using System.Collections;
 3 using UnityEngine.UI;
 4 using UnityEngine.EventSystems;
 5 
 6 /// <summary>
 7 /// 摇杆
 8 /// </summary>
 9 public class JoyStickScript : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
10 {
11 
12     GameObject Player; //移动的对象
13 
14     Vector3 originPosition;//起点坐标
15     Vector3 newPosition;
16     public float Radius = 40; //滚动的最大半径
17     float horizontal;
18     float vertical;
19     float speed;
20     void Awake()
21     {
22         Player = GameObject.FindWithTag("Player");
23     }
24 
25     // Use this for initialization
26     void Start()
27     {
28         //originPosition = transform.position;//记录原点位置
29     }
30 
31     // Update is called once per frame
32     void Update()
33     {
34         //float horizontal = Input.GetAxis("Horizontal");
35         //float veritcal = (transform.position.y - originPosition.y) / Radius;
36         //vertical = (transform.position.y - originPosition.y) / Radius;
37         //horizontal = (transform.position.x - originPosition.x) / Radius;
38         //Player.transform.Translate(horizontal, vertical, 0);
39         //Debug.Log(vertical);
40 
41     }
42 
43     public void OnEndDrag(PointerEventData eventData)
44     {
45         transform.position = originPosition; //归位到原点
46     }
47 
48     Vector3 dir;
49     public void OnDrag(PointerEventData eventData)
50     {
51 
52         dir = (Input.mousePosition - originPosition).normalized;
53 
54         transform.position = Input.mousePosition; //设置当前摇杆位置
55 
56         //当超过了外面的圆圈
57         if (Vector3.Distance(Input.mousePosition, originPosition) > Radius)
58             transform.position = originPosition + dir * Radius;
59 
60         //vertical = (transform.position.y - originPosition.y) / Radius;
61         //horizontal = (transform.position.x - originPosition.x) / Radius;
62         print(originPosition + dir * Radius);
63         Player.transform.position = dir * Time.deltaTime;
64     }
65 
66     public void OnBeginDrag(PointerEventData eventData)
67     {
68         originPosition = transform.position;//记录原点位置
69     }
70 }

 

UGUI实现摇杆

标签:

原文地址:http://www.cnblogs.com/nsky/p/4608437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!