新手笔记:箭头随鼠标方向不同而改变 VR资源

锐剑 2017-10-23 16:29:05
描述:以炉石传说为例子,鼠标拖拽图片出现箭头,随着鼠标拖拽的距离方向,箭头改变相应的属性1.搭建UI,用了四张Image,其中一个是箭头图片, 如下图


这里Arrow的Width和Height为图片原来大小,scale设为了0.2,0.2,,进行九宫格切割,将Arrow的Image中的Image Type设为Sliced,,保证箭头不变形;Pivot.y设为0,保证箭头只向正方向变化


2.在Arrow上添加脚本,Arrow.cs;  分别在三张Image上添加同一个脚本ImageBg.cs。
Arrow.cs:
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Arrow : MonoBehaviour {
 
    public static Arrow Instance;
 
    RectTransform rt; 
    Vector3 angleV3;  
 
    private void Awake()       //用了三张图片,所以加了单例
    {
        Instance = this;
        gameObject.SetActive(false);      //Arrow初始状态设为false
        rt = GetComponent<RectTransform>();
        angleV3 = new Vector3(0, 0, 0);  //初始位置
    }
 
        //拖拽开始时的方法
    public void StartDrag(Vector3 imageBgPosition)    //传入Image的位置
    {
        gameObject.SetActive(true);     Arrow状态设为true
        transform.position = imageBgPosition;  
    }
         
        //拖拽时的方法
    public void OnDraging(float distance, float angle) 
    {
        rt.sizeDelta = new Vector2(rt.sizeDelta.x, distance / rt.localScale.y);  //改变Arrow的大小
        angleV3.z = angle - 90f;
        transform.localRotation = Quaternion.Euler(angleV3);  ////改变Arrow的方向
    }
 
        //结束拖拽时方法
    public void EndDrag()
    {
        gameObject.SetActive(false);   //Arrow状态设为false
        rt.sizeDelta = new Vector2(rt.sizeDelta.x, 0); 
        transform.localRotation = Quaternion.identity;
    }
 
}

ImageBg.cs
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
 
public class ImageBg : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public GameObject arrow;
 
 
        //对应状态Arrow中方法的调用,出入对应参数
         
    public void OnBeginDrag(PointerEventData eventData)
    {
        Vector3 pos = transform.position;
        Arrow.Instance.StartDrag(pos);   //
    }
 
    public void OnDrag(PointerEventData eventData)
    {
        float distance = Vector2.Distance(transform.position, Input.mousePosition);
 
        Vector2 v2 = (Input.mousePosition - transform.position).normalized;
        float angle = Mathf.Atan2(v2.y, v2.x) * Mathf.Rad2Deg;
        Arrow.Instance.OnDraging(distance, angle);
    }
 
    public void OnEndDrag(PointerEventData eventData)
    {
        Arrow.Instance.EndDrag();
    }
}



3.实现如下:
 
 
99VR视界二维码
热门推荐
Hot Recommended
在线客服