unity 鼠标移入弹出UI

外部调用 show 和Hide方法

using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

public class ShowInfo : MonoBehaviour {

    private bool _isshowing = false;
    public Canvas Canvas;

    // Use this for initialization
    void Start()
    {
        Hide();
    }

    // Update is called once per frame
    void Update()
    {

    }
    public void Hide()
    {
        transform.DOScale(Vector3.zero, 0.3f);
        _isshowing = false;
    }

    public void Show()
    {
        transform.DOScale(Vector3.one, 0.3f);
        _isshowing = true;
    }
    void FixedUpdate()
    {
        if (_isshowing)
        {
            Vector2 localPoint = Input.mousePosition - new Vector3(Screen.width * 0.5f, Screen.height * 0.5f);
            Vector3 pos = (localPoint / Canvas.transform.localScale.x);
            pos.x += 10f;
            transform.DOLocalMove(pos, 0.01f);
        }
    }
}


Unity引擎中,如果你想要实现当鼠标移动到3D场景中的某个物体上时,UI元素也随之跟随,通常需要通过结合Input System、Raycasting以及UI Anchors的功能来完成。以下是基本步骤: 1. **启用Input System**:Unity 2018.4及以上版本引入了新的Input System组件,用于处理用户的输入事件,包括鼠标点击。 2. **创建Raycast功能**:在UI元素上添加Raycast功能,比如`Canvas Raycast Target`组件。这将允许你在鼠标点击时检测到与之相交的3D对象。 3. **编写脚本**:创建一个C#脚本,添加`OnPointerEnter`和`OnPointerExit`方法,分别在鼠标移入和移出物体时触发。在`OnPointerEnter`里,检查Raycast结果,如果找到目标3D对象,更新UI元素的位置,使其相对于该对象定位。 ```csharp using UnityEngine; using UnityEngine.UI; public class FollowMouseToObject : MonoBehaviour { public RectTransform UIParent; // UI父容器 private Canvas canvas; // 假设已经初始化过的Canvas private void Start() { canvas = GetComponent<Canvas>(); } void OnPointerEnter(PointerEventData eventData) { RaycastHit hit; if (Physics.Raycast(eventData.mousePosition, Vector3.down, out hit)) { var targetGameObject = hit.transform.gameObject; // 更新UIParent锚点位置,让它看起来像是跟随到了targetGameObject UIParent.anchoredPosition = new Vector3(hit.point.x, UIParent.anchoredPosition.y); } } void OnPointerExit(PointerEventData eventData) { UIParent.anchoredPosition = default; // 当离开物体时恢复默认位置 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值