unity 鼠标事件

 1.1键盘触发事件

Input.GetMouseButtonDown(0) 鼠标按下那一刻触发(点击屏幕)
Input.mousePosition 鼠标的坐标
Input.GetKeyDown(KeyCode.Space) 按键被按下那一刻进行触发(点击空格)
Input.GetKey()  按键一直按着时触发
Input.GetKeyUp () 按键被按下后抬起时触发 
Input.GetMouseButtonUp()  鼠标抬起的那一刻时触发
Input.GetMouseButton(0/1/2)  1:左键 2:右键 3:中键 鼠标一直按着时触发

1.2D中鼠标方法

事件 描述
OnMouseDown 当鼠标点击才会触发该事件函数"
OnMouseUp 当鼠标点击后抬起的时候(瞬间),才会触发该事件函数
OnMouseDrag 当鼠标按下的过程当中拖拽才会触发该事件函数
OnMouseEnter 当鼠标移动到该物体上的时候(瞬间),才会触发该事件函数
OnMouseExit 当鼠标移出该物体的时候(瞬间),才会触发该事件函数
OnMouseOver 当鼠标在物体上的时候,才会触发该事件函数
OnMouseUpAsButton 鼠标只有在点击和抬起都在一个物体上,该事件函数才会触发,并且是在抬起的那一刻触发。
当鼠标点击该物体,但是在物体之外抬起,该事件函数是不会触发的,(在UGUI按钮方面使用较多)

//OnMouseEnter与OnMouseOver的区别就是前者是移到物体的一瞬间触发一次,后者只要在该物体上就会触发。

1.3D游戏中鼠标触发事件

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEditor.UI;

//必须引MonoBehaviour, IPointerClickHandler, IBeginDragHandler
public class Joystick : MonoBehaviour, IPointerClickHandler, IBeginDragHandler, IEndDragHandler, IDragHandler
{
    private RectTransform rectTransform;//获取当前ui的rectTransform

    private RectTransform rf;

    void Start()
    {
        //获取到摇杆物体
        GameObject go = this.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject;
        rectTransform = go.GetComponent<RectTransform>();
        Debug.Log(this.transform.name);
        Debug.Log(rectTransform.name);
    }


    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("开始拖拽OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("OnDrag");

        Vector3 ui;
        //物体的移动【移动的transform,移动的位置,移动的角度,移动后输出的位置】
        RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, eventData.position, eventData.enterEventCamera, out ui);
        rectTransform.position = ui;
    }


    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("结束拖拽OnEndDrag");
    }


    public void OnPointerClick(PointerEventData eventData)
    {
        Debug.Log("检测到点击了OnPointerClick");
        Debug.Log();

       
    }

}


 

猜你喜欢

转载自blog.csdn.net/qq_38092788/article/details/132025660