//脚本实现侦听鼠标行为,并实现鼠标划入放大物体,鼠标划出复原物体,以及拖拽物体
脚本需要挂给侦听对象
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);//关闭文本框
}
}
如果想要侦听并操作三维物体,需要给3D场景摄像机添加一个物理射线发射器,把脚本挂给被侦听的对象即可。UGUI为啥不需要呢,因为画布中有一个看不见的摄像机负责发射射线其实就是画布自己,他身上有射线发射脚本叫Graphic Raycaster
侦听交互3D物体的代码,直接拖到任意被侦听的3D物体上即可,确保摄像机看见他
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Raycast : MonoBehaviour,IBeginDragHandler,IPointerClickHandler,IPointerExitHandler,IPointerEnterHandler,IDragHandler
{
Vector3 tempscale;
void Start()
{
tempscale = this.transform.localScale;
// Vector3 temppos= Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("点击了物体");
}
public void OnPointerExit(PointerEventData eventData)
{
this.transform.localScale = tempscale;
throw new System.NotImplementedException();
}
public void OnPointerEnter(PointerEventData eventData)
{
Debug.Log("点击了物体");
this.transform.localScale *= 1.5f;
}
public void OnDrag(PointerEventData eventData)
{
Debug.Log("拖拽了物体"+ Camera.main.ScreenToWorldPoint(Input.mousePosition));
this.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y,2f));
}
// Start is called before the first frame update
}
实现了鼠标划上去物体变大 ,拖拽3D物体