软件编程
位置:首页>> 软件编程>> C#编程>> unity 鼠标悬停事件操作

unity 鼠标悬停事件操作

作者:sogooday  发布时间:2022-12-19 05:36:03 

标签:unity,鼠标,悬停

笔者在网上发现了,很多种方法 ,当然咱们找最好用的,也简单的 下面废话不多说直接上代码 我在啰嗦几句 第一这个脚本挂在需要相应的游戏体上 第二被挂游戏体必须带有collider, 第三仅仅制作完上面的两步 本应该没有问题,

笔者又发现一个问题 就是只有鼠标在物体的右上方才会很灵敏的相应到 在在左下方反而没什么反应 ,为此笔者在脚本上加上了一句


this.GetComponent<BoxCollider> ().size = new Vector3 (1.5f, 1.5f, 1.5f);

原来物体的size 为(1,1,1) 我的目的是加大物体本身的碰撞体 结果顺利的实现了

下面是完整


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shubiaoxuanting : MonoBehaviour{
   bool ischanger; //上移动 0为未上移 1为上移
   int move_up=0;
   void Start () { ischanger = false; //扩大碰撞体的尺寸 方便检测鼠标悬停            
      this.GetComponent<BoxCollider> ().size = new Vector3 (1.5f, 1.5f, 1.5f);
      //给麻将初始状态的位置 this.transform.position = new Vector3        
      (this.transform.position.x, 0, this.transform.position.z); }
       //鼠标在物体上面引起的动作 void OnMouseOver(){ ischanger = true;    
      this.transform.position = new Vector3 (this.transform.position.x, 0.2f,
     this.transform.position.z); }
    // void OnMouseEnter(){
    // ischanger = true;
    // move_up = 1;
    // Debug.Log ("3333333");
    // // }
    //鼠标不再上面引起的动作
    void OnMouseExit(){
       ischanger = false;
       this.transform.position = new Vector3 (this.transform.position.x, 0, this.transform.position.z);
   }  /鼠标按下

/鼠标按下
void OnMouseDown(){  
}
}
//鼠标松开
//鼠标松开
void OnMousePut(){}
void OnMousePut(){}
void Update () {
// if (ischanger){
   //Debug.Log ("33333");
   //this.transform.position = new Vector3 (this.transform.position.x, 0.2f, this.transform.position.z)
} else {
// this.transform.position = new Vector3 (this.transform.position.x, 0, this.transform.position.z);
// }}}

补充:Unity UGUI Button鼠标的悬停事件(利用重写unity中的button来实现)

我就废话不多说了,大家还是直接看代码吧~


using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class LearnButton : Button
{
   ///
   /// 配合Unity的其他方法使用,就能达到你想要的效果!这里只是抛砖引玉,大家有更好的方法欢迎跟我交流!
   ///
   ///
   ///
   protected override void DoStateTransition(SelectionState state, bool instant)
   {

base.DoStateTransition(state, instant);
       switch (state)
       {

case SelectionState.Disabled:
               break;
           case SelectionState.Highlighted:
               Debug.Log("鼠标移到button上!");
               break;
           case SelectionState.Normal:
               Debug.Log("鼠标离开Button!");
               break;
           case SelectionState.Pressed:
               break;
           default:
               break;
       }
   }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

来源:https://blog.csdn.net/huhudeni/article/details/72587191

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com