【UGUI】课堂案例:测试事件侦听、缩放拖动物体

 //脚本实现侦听鼠标行为,并实现鼠标划入放大物体,鼠标划出复原物体,以及拖拽物体

脚本需要挂给侦听对象

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using TMPro;

//改脚本实现侦听鼠标行为,并实现鼠标划入放大物体,鼠标划出复原物体,以及拖拽物体
public class EventsystemTest : MonoBehaviour,IBeginDragHandler,IDragHandler,IPointerEnterHandler,IPointerExitHandler
{
    Vector3 OriginScale;//声明一个三维向量用来存储被拖拽物体的,拖拽前的坐标,便于将来恢复
    GameObject OnDiscrip;//声明一个变量存储一个 描述文本,将来用于描述物体介绍
    private void Awake()
    {
        
        OnDiscrip = GameObject.Find("Descript");//通过名字从外部拿到一个描述文本,用来显示物体介绍
    }

    void Start()
    {
        OnDiscrip.SetActive(false);//开始把文本框关闭
        OriginScale = this.transform.localScale;//存储当前物体的原始缩放数值
    }

    public void OnBeginDrag(PointerEventData eventData)//这是一个接口,固定格式,无需修改
    {
        Debug.Log("开始拖拽");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("拖拽中");
        Vector3 oneV = new Vector3(Input.mousePosition.x, Input.mousePosition.y, this.transform.position.z);
        this.transform.position = oneV;//鼠标坐标赋值给拖动的对象
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
         Debug.Log("鼠标滑入");
        this.transform.localScale *= 1.2f;//放大当前物体1.2倍
        if (this.gameObject.name == "YellowImage")
        {
            OnDiscrip.SetActive(true);//打开文本框
            //填入一句话给文本框
            OnDiscrip.GetComponent<TextMeshProUGUI>().text = "轩辕:这是一件衣服,传说有上古的力量";
        }
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("鼠标滑出");
        this.transform.localScale = OriginScale;//让物体缩放归位,回到原始状态
        OnDiscrip.SetActive(false);//关闭文本框
    }
}

如果想要侦听病操作三维物体,需要给摄像机添加一个物理射线发射器,把脚本挂给被侦听的对象即可

猜你喜欢

转载自blog.csdn.net/leoysq/article/details/134739506
今日推荐