A-Frame中文教程

光标

光标组件允许我们通过点击和凝视与实体交互。光标组件被用于 光线投射(raycaster)来实现:

当鼠标单击时,与光标相交的最近可见实体(如果有)将发出 单击事件。注意光标组件只是应用了光线投射行为。要为光标提供形状或外观,可以应用 geometrymaterial组件。

例子

例如,我们可以创建一个固定在屏幕中心的环形光标。为了将光标固定在屏幕上,使光标始终显示在任何地方,我们将其作为活动 相机(camera)的一个子实体。我们把它放在相机前面,在负Z轴上。当光标单击box时,我们可以监听click事件。

            
<a-entity camera>
<a-entity cursor= "fuse: true; fuseTimeout: 500"
position="0 0 -1"
geometry="primitive: ring; radiusInner: 0.02; radiusOuter: 0.03"
material="color: black; shader: flat">
</a-entity>
</a-entity>
<a-entity id= "box" cursor-listener geometry= "primitive: box" material= "color: blue"></a-entity>
            
// Component to change to random color on click.
AFRAME.registerComponent('cursor-listener', {
init: function( ){
varCOLORS = ['red','green','blue'];
this.el.addEventListener('click', function( evt){
varrandomIndex =Math.floor(Math.random() * COLORS.length);
this.setAttribute('material','color', COLORS[randomIndex]);
console.log('I was clicked at: ', evt.detail.intersection.point);
});
}
});

属性

Note, to further customize the cursor component, we can set the properties of the raycaster component.

属性 描述 默认值
fuse 光标是否是基于凝视动作的 桌面上为,移动设备为true
fuseTimeout 触发基于凝视的单击事件之前要等待多长时间(以毫秒为单位)。 1500

事件(Events)

事件 描述
click 如果单击当前相交实体(无论是通过鼠标点击还是通过凝视动作),则从光标和相交实体上发出。
fusing 当开始凝视时和凝视中,从光标和相交实体上发出。
mousedown 在canvas元素上的鼠标按下时,从光标和相交实体(如果有)上发出。
mouseenter 当光标与实体相交时,从光标和相交实体(如果有)上发出。
mouseleave 当光标不再与先前相交的实体相交时,从光标和相交实体(如果有)上发出。
mouseup 在canvas元素上的鼠标松开时,从光标和相交实体(如果有)上发出。

状态(States)

光标将在某些事件上向光标实体添加状态:

状态 描述
cursor-fusing 当光标停留在某个实体上时。
cursor-hovering 当光标悬停在另一个实体上时添加。

光标将在某些事件上向相交实体添加状态:

状态 描述
cursor-hovered 当光标悬停在相交实体上时添加到该实体。

通过光线投射(Raycaster)组件配置光标

光标建立在光线投射组件之上并依赖于该组件。如果要自定义光标的光线投射部分,可以通过更改 光线投射组件属性。假设我们希望设置最大距离,减少检查相交点的频率,并设置可单击的对象:

            
<a-entity cursor raycaster= "far: 20; interval: 1000; objects: .clickable"></a-entity>

基于凝视的光标(fuse-based或gaze-based)

如果我们将光标设置为fuse-based,那么如果用户凝视一个实体一段时间,光标将触发一次单击。想象一下,一束激光绑在用户的头上,然后激光延伸到场景中。如果用户盯着一个实体足够长的时间,然后光标将触发单击。

基于凝视的VR交互的优势在于,它不需要头戴设备以外的额外输入设备,缺点是它需要用户经常转头。

添加视觉反馈

要向光标添加视觉反馈以显示光标单击或凝视发生的时间,可以使用 动画系统。当光标与实体相交时,它将发出一个事件,并且动画系统将使用 begin属性来处理该事件:

            
<a-entity cursor= "fuse: true; fuseTimeout: 500"
position="0 0 -1"
geometry="primitive: ring"
material="color: black; shader: flat">
<a-animation begin= "click" easing= "ease-in" attribute= "scale"
fill="backwards"from="0.1 0.1 0.1"to="1 1 1"></a-animation>
<a-animation begin= "cursor-fusing" easing= "ease-in" attribute= "scale"
fill="forwards"from="1 1 1"to="0.1 0.1 0.1"></a-animation>
</a-entity>

在线试试: 带有视觉反馈示例的光标