将EventListener'click'添加到资产中

问题描述 投票:0回答:1

我在javascript中有此代码

let starting = -45, forward1 = 1, forward2 = 1, forward3 = 1;
let ball1;
let cannon1;
let ship;

window.onload = function() {
  ball1 = document.getElementById("ball1");
  cannon1 = document.getElementById("cannon1");

  cannon1.addEventListener("click",function(obj){
    ball1.fire = true;
  })
  update();

};

function update(){
  if(ball1.fire){
    starting += forward1;
    ball1.setAttribute("position", {x:-starting - 20, y:7, z:0})
  }
  if(starting >= 100){
    ball1.setAttribute("position", {x:0, y:7, z:50})
    starting = 0;
    ball1.fire = false;
  }

  setTimeout(update,10);
};

这是我的html

]<!DOCTYPE html>
<html>

  <body>
    <a-scene id="scene">

      //camera
      <a-camera rotation = "0 90 0" position = "0 5 0">
            <a-cursor></a-cursor>
      </a-camera>

      //other
      <a-sky src = "sky.jpg"></a-sky>
      <a-plane position = "2 0 -20"rotation = "-90 0 0"width ="5000" height = "5000" material = "src:ocean.jpg;repeat: 1 1"></a-plane>

      //3d models
      <a-assets>
        <a-asset-item id="ship" src="ship/scene.gltf"></a-asset-item>
        <a-asset-item id="cannon1" src="cannon/scene.gltf"></a-asset-item>
      </a-assets>

      //ship
      <a-gltf-model src="#ship" position = "0 0 0" scale="0.5 0.5 0.5"></a-gltf-model>

      //cannons
      <a-gltf-model src="#cannon1" rotation = "0 0 0" position = "-4.7 4.1 2.2" scale="0.02 0.02 0.025"></a-gltf-model> 

      //balls
      <a-sphere id ="ball1" color="black" position = "-4.7 4.1 2.2" radius="0.3" rotation = "0 0 0"></a-sphere>

        //cannon 1
        <a-box position = "-2 6 -10" color="black" depth="2" height="2" width="2"></a-box>
        <a-box position = "2 6 -10" color="black" depth="2" height="2" width="2"></a-box>
        <a-box id = "fire1" position = "0 7 -12" color="brown" depth="7" height="2" width="2"></a-box>
        <a-box id ="myBox1" position = "0 7 -10" color="red" rotation = "0 0 0" ></a-box>   

    </a-scene>
  </body>
</html>

这只是说,如果用户单击ID为“ cannon1”的对象,球将向前射击。

此确切的代码与ID为“ cannon1”的a一起使用,但是当我导入3d模型的大炮并将其分配为“ cannon1”时,该代码似乎不起作用

javascript aframe
1个回答
0
投票
<a-gltf-model id="shipEntity" src="#ship" position = "0 0 0" scale="0.5 0.5 0.5"></a-gltf-model>

您需要将click事件侦听器附加到实体,而不是资产引用。

shipEntity.addEventListener('click',()=>ball1.fire=true);
© www.soinside.com 2019 - 2024. All rights reserved.