我正在尝试做有史以来最简单的事情之一,将事件侦听器添加到A-Frame中的元素。但是,我是A-Frame的新手,遇到了很多问题。甚至不是代码没有在鼠标按下时旋转对象,而是通过控制台注册了否点击。我认为这可能与以下事实有关:“ fishing-logic”组件已添加到位置为(0,0,0)的父级中,而我尝试单击的模型部分的位置为(0,1,-3),但是即使我将“ fishing-logic”组件添加到,它仍然不会注册点击。谁能帮助我了解我在做什么错?
AFRAME.registerComponent('fishing-logic', {
init: function() {
var el = this.el;
var isDragging = false;
el.addEventListener('mouseenter', function() {
console.log("Calling mouse enter!");
});
el.addEventListener('mouseleave', function() {
console.log("Calling mouse leave!");
});
el.addEventListener('mousedown', function(evt) {
console.log("Calling mouse down!");
isDragging = true;
if(this.isDragging){
el.object3D.rotation.x += Math.PI;
}
});
el.addEventListener('mouseup', function(evt) {
console.log("Calling mouse up!");
});
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>A-Frame Starter</title>
<meta name="description" content="Base Project">
<script src="https://aframe.io/releases/0.9.0/aframe.min.js"></script>
<script src="https://unpkg.com/aframe-event-set-component@4.2.1/dist/aframe-event-set-component.min.js"></script>
<script src="//cdn.rawgit.com/donmccurdy/aframe-extras/v6.0.0/dist/aframe-extras.min.js"></script>
<script src="//cdn.rawgit.com/donmccurdy/aframe-physics-system/v3.3.0/dist/aframe-physics-system.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<a-scene>
<a-assets><a-asset-item id="fishing_pole" src="assets/Fishing_Pole_01.gltf"></a-assets>
<a-entity fishing-logic>
<a-gltf-model src="#fishing_pole"
position="0 1 -3"
rotation="0 0 0"
scale="0.1 0.1 0.1"></a-gltf-model>
<a-entity line="start: 0, 3.3, -2.9; end:0 0 -5; color: white"></a-entity>
</a-entity>
<a-sky color="#111133"></a-sky>
<a-plane rotation="-90 0 0" color="#000011" width="64" height="64" depth="64" shadow></a-plane>
</a-scene>
<div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div>
<script src="https://button.glitch.me/button.js"></script>
</body>
</html>
答案 0 :(得分:0)
问题在于,由于fishing-logic在a-gtlf模型的父a实体上,因此它需要raycaster的“可交互”查询选择器/类。可以在下面的代码片段中看到。然后,我在a-entity中的fishing-logic组件旁边添加了可交互组件,并开始注册点击。
AFRAME.registerComponent('interactable', {
init() {
let el = this.el;
let originalColor = el.getAttribute('material').color;
el.addEventListener('raycaster-intersected', function() {
el.setAttribute('material', 'color', '#24CAFF');
});
el.addEventListener('raycaster-intersected-cleared', function() {
el.setAttribute('material', 'color', originalColor);
});
el.addEventListener('mousedown', function() {
el.body.applyImpulse(
new CANNON.Vec3(0, 3, 0),
new CANNON.Vec3().copy(el.getAttribute('position'))
);
});
}
});