Is there a way to direct an arrow towards an item in Aframe?

I'm trying to figure out how to point an arrow at a specific object in an Aframe scene. The arrow and object will be located at random positions, with the arrow initially facing "up" along the z-axis. I have some ideas on how to achieve this, but I'm unsure of the exact implementation. Can someone provide guidance?

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Hello, WebVR! • A-Frame</title>
    <meta name="description" content="Hello, WebVR! • A-Frame">
    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
  </head>
  
  <body>
    <a-scene background="color: #ECECEC">
      <a-sphere id="sphere" position="6 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
      
      <a-entity id="arrow"></a-entity>
    </a-scene>
  </body>
  
  <footer>
    <script>
      const loader = new THREE.GLTFLoader();
      loader.load("https://cdn.glitch.com/6ff6d9d5-f662-48cc-8e22-30eaf4dfc295%2Farrow.glb?v=1612557642197", function ( model ) {
          model.scene.traverse(node => {
              if (node.geometry && node.material) {
                  geometry = node.geometry;
              }
          })
          geometry.scale( .5,.5,.5 );
          geometry.computeVertexNormals();

          material = new THREE.MeshLambertMaterial({ flatShading: true, color: 0xFF0000 });
          mesh = new THREE.Mesh(geometry, material);
        
          document.getElementById('arrow').object3D.add(mesh);
        
          const arrow = document.getElementById('arrow').object3D;
          arrow.position.set(1,1,1);
        
          const sphere = document.getElementById('sphere').object3D;
          
          // The angleTo method from Three.js seems promising. 
          // However, it only returns one angle. If I can find the axis connecting
          // the arrow and sphere, I might be able to apply this angle to the arrow.
          const ang = new THREE.Vector3(arrow.position.x, arrow.position.y, arrow.position.z).angleTo(new THREE.Vector3(sphere.position.x, sphere.position.y, sphere.position.z));
        
          arrow.rotation.set(--need to determine these angles--);

      });
          
      
    </script>
  </footer>
</html>

Answer №1

To ensure your arrow always faces the specified position, use the .lookAt() method:

var targetPosition = new THREE.Vector3(x, y, z);
arrow.lookAt(targetPosition);

Ensure that the arrow is pointing in the direction of the -z axis. If the position changes, simply call the method again with the updated vector.

Check out the documentation for more information!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Even with THREE.SmoothShading enabled, the edges are still visible on a THREE.CylinderGeometry

My goal is to achieve a flawless shading effect on a cylinder using three.js. When I set the shading parameter of my material to THREE.SmoothShading, there is a noticeable improvement in appearance, but the outlines of the faces are still visible: What co ...

Confusion with Javascript callbacks - seeking clarity

I am having difficulty grasping the concept of callback functions. I know that they are functions passed as parameters to other functions. My assumption was that when a function is passed as a parameter, it would be recognized as a callback function and ex ...

What could be causing the malfunction of client components in NextJS 13.3.0 with experimental features?

My understanding of the beta documentation suggests that I need to include "use client" at the top of my client component in order for it to be defined as such. This allows me to use it within server components, leaves, or layouts. With that in ...

Is there a way to retrieve the ID from a span and convert it into a string format?

let wordSpan = '<span class="we w_o_r_d_s" id="we" contenteditable="false">we</span>' console.log(wordSpan.id); console.log(wordSpan.attr('id')); console.log(wordSpan.getAttribute('id')); let newDiv = document.c ...

Steps for integrating a valid SSL certificate into a Reactjs application

After completing my ReactJS app for my website, I am now ready to launch it in production mode. The only hurdle I face is getting it to work under https mode. This app was developed using create-react-app in a local environment and has since been deployed ...

The Antd table documentation mentions that rowKey is expected to be unique, even though it appears they are already

Having trouble with a React code issue. I have a list of products, each with an array of 7 items that contain 40 different data points. This data is used as the source for a table. {label : someStringLabel, key: someUniqueKey, attribute1: someInt,..., at ...

What could be causing the issue with the functionality of third-level nested SortableJS drag-and-drop?

I am currently utilizing SortableJS to develop a drag-and-drop form builder that consists of three types/levels of draggable items: Sections, Questions, and Options. Sections can be dragged and reorganized amongst each other, Questions can be moved within ...

Using PHP to pass values from a MySQL database to JavaScript

hello, $i=0; while($row = $result->fetch_assoc()) { echo " <tr><td>".$row["Number"]."</td><td>".$row["MusikName"]." ".$row["MusikURL"]."</td></tr>"; This portion is successful...it displays -&g ...

Generating a primary XML element encompassing multiple namespaces

I am currently working on integrating Restful services with Backbone.js framework. In this project, I need to send XML data and add multiple namespaces to it. Here is the snippet of my current JavaScript code: var mainNamespace = "xmlns='http://serv ...

Error: 'fs' module not found in React.js and cannot be resolved

Encountering issues with tatum io v1 + react? Developers have acknowledged that it's a react problem which will be addressed in V2. In the meantime, you can utilize tatum io V1 with node js. I've included all dependencies that could potentially ...

Do you know of a solution to fix the Stylelint error regarding semicolons when using CSS variables?

React.js Css in JS(Emotion) The components above are part of this setup. Here is the configuration for Stylelint: module.exports = { extends: [ "stylelint-config-standard", "./node_modules/prettier-stylelint/config.js", ], ...

When incorporating reduce into your code, remember to expect an undefined

Imagine you have an array like this: const novels = [ { id: 1, name: 'The Da Vinci Code', genre: 'Mystery', author: { name: 'Dan Brown', birthYear: 1964, }, releaseYear: 2003, }, { ...

Bringing the Jquery cursor into focus following the addition of an emoji

Looking to add emojis in a contenteditable div but facing an issue with the cursor placement. Here is a DEMO created on codepen.io. The demo includes a tree emoji example where clicking on the emoji adds it to the #text contenteditable div. However, after ...

The event handler onClick is unresponsive in the button element within a React component

Hey there, I'm new to React and I'm having an issue with a class-based component. Below is my component that I'm calling inside another React component. I just want the temp function to be called when onClick is triggered, but it's not ...

Tips for showing informational text when the dialogue box is open

When I open my help dialog, the information texts are not displayed right away. They only appear when I click on the subsection. Is there a way to show them as soon as the dialog box is opened? Any suggestions or assistance would be greatly appreciated. H ...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

Error message: Object literal is limited to declaring existing properties

The source code was obtained from this Codesandbox demo: CodeSandbox - Cover Image Example Subsequently, an .eslintrc configuration file was generated with the following content (the only content present): { "extends": "react-app" } However, a TypeScri ...

The execution of the code may encounter errors initially, but it generally runs without any issues on subsequent attempts

I recently developed a piece of code to ascertain whether a value in the database is null or not. Here's the snippet: var table; var active = false; function CheckActive(table){ this.table = "table" + table + ""; var db = window.openDatabas ...

Replacing multiple attributes within a complex HTML opening tag using Node.js regular expressions

I'm currently working on a Node.js project where we need to search through several PHP view files and replace certain attributes. My goal is to extract the values of HTML open tag attributes and replace them. To clarify, I want to capture anything in ...

Guide to organizing an array of objects based on the month and year they belong to?

I currently have an array of objects structured as follows: entries: [ { id:1, text: "Lorem ipsum", timeStamp:"Thu, 01 Jun 2018" }, { id:3, text:"Lorem ipsum", timeStamp:"Thu, 24 May 2018" }, { ...