当用户将鼠标悬停在它上面时,如何让我的实体旋转?

How can I make my entity spin when the user hovers over it?

我正在使用事件集组件来使我的对象模型在光标悬停在它上面时增加比例。

这工作正常。

但是我怎样才能让它旋转并增加尺寸呢?

我在 AFrame 文档上找到了以下代码,但我不知道如何实现它,所以它会在鼠标悬停在实体上时触发。

<a-animation attribute="material.opacity" begin="fade" to="0"></a-animation>

如果正确设置开始事件,引用的动画将起作用:

<a-animation attribute="rotation"
             dur="2000"
             begin="mouseenter"
             to="0 360 0"
             repeat="1"><a-animation>

在鼠标进入时,动画触发,并旋转实体一次。


为了更好地控制你所做的事情,你需要深入研究组件。

1. 我能想到的最简单的方法是同时使用动画组件和您自己的组件。您需要设置一个监听 mouseenter/mousexit 的组件并触发动画:

AFRAME.registerComponent('mouseenterhandler', {
  init: function () {    
  let el = this.el; //Your element reference
  el.addEventListener('mouseenter, function () {
      // get the rotation, by getAttribute, or by accessing the 
      //object3D.rotation
      let rotation = el.getAttribute('rotation');
      //lets rotate it to the same position
      rotation.y += 360; 
      //set the animation component accordingly:
      el.children[0].setAttribute('to',rotation);
      //emit the 'begin' event:
      el.emit('startrotating');
      });
    }   
});

必要时快速改进:在触发动画时禁用侦听器。使用布尔值打开 mouseenter 事件和 animationend 事件。

2. 可以选择不使用动画组件,如果光标结束,则检查tick()。如果是这样,请将元素旋转 actualRotation.y+0.1(或任何其他所需的旋转)。
如前所述,您可以通过 getAttribute() 或 el.object3D.rotation 访问旋转。


至于比例,如果您需要在 mouseenter 事件中旋转 + 重新缩放对象,只需添加另一个动画,然后像我对旋转所做的那样使用它。
我不确定它通常是如何完成的,根据我的经验,动画很好,当没有那么多交互时,因为它们有时会做意想不到的事情,你必须 predict/find 出来,并防止。
另一方面,如果旋转增量太大,手动制作任何动画(在 tick 上更改属性)可能看起来很慢。
你需要尝试一下,找出最适合你的.

由于您在评论中要求使用不同的方法,我建议使用像我写的那样的多用途组件:

AFRAME.registerComponent('event-animate', {
schema: {
    target: {type: 'selector'},
    aevent: {default: 'animation1'},
    triggeraction: {default: 'click'}
},

init: function () {
    var data = this.data;

    this.el.addEventListener(data.triggeraction, function () {
        data.target.emit(data.aevent);
    });
}

});

所以在 HTML 中它看起来像这样:

<a-entity id="object1" 
          event-animate="target:object1;    
          triggeraction:mouseenter; 
          aevent:eventstart">
<a-animation attribute="scale" 
             dur="5000" 
             begin="eventstart" 
             from="1" 
             to ="5" 
             direction="alternate"> 
</a-animation>
<a-animation attribute="rotation" 
             dur="5000" 
             begin="eventstart" 
             from="0 0 0" 
             to="0 360 0" 
             direction="alternate">
</a-animation>
</a-entity>

方向="alternate"应该把它带回原来的位置。