You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ursina中实现Entity鼠标悬停时切换纹理?

Ursina实体鼠标悬停切换纹理实现方案

在Ursina中,Entity类虽然没有直接的highlight_texture参数,但可以通过监听鼠标进入/离开事件,或者检测实体的hovered属性来实现悬停切换纹理的效果,以下是针对你的Door类的具体实现:

实现思路

  1. 预加载正常状态和悬停状态的两张纹理,避免重复加载资源
  2. 通过Ursina内置的鼠标事件(mouse_enter/mouse_exit)触发纹理切换,这种方式仅在状态变化时执行代码,性能更优

完整代码示例

from ursina import *

app = Ursina()

class Door(Entity):
    def __init__(self, position=(0, 0, 0), blocked=False, parent=None):
        # 预加载两张纹理
        self.normal_texture = load_texture('assets/door')
        self.hover_texture = load_texture('assets/door_hovered')
        
        super().__init__(
            model='cube',
            position=position,
            texture=self.normal_texture,  # 初始使用正常纹理
            scale=(2, 3.5, .1),
            collider='box'  # 必须添加碰撞体,否则无法检测鼠标悬停
        )

    # 鼠标进入实体时触发
    def mouse_enter(self):
        self.texture = self.hover_texture

    # 鼠标离开实体时触发
    def mouse_exit(self):
        self.texture = self.normal_texture

# 创建测试门实体
Door(position=(0,0,0))

app.run()

关键说明

  • 碰撞体:必须给Entity添加collider(比如'box'),Ursina依赖碰撞体来检测鼠标是否悬停在实体上,没有碰撞体的话鼠标事件和hovered属性都无法生效
  • 纹理预加载:在__init__里提前加载两张纹理,避免每次切换时重复读取文件,提升运行效率

内容的提问来源于stack exchange,提问作者Vagif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 01:09:57