Manipulate object position using Aframe and three.js

I'm working on developing a game using A-frame. I'm trying to add a shooting effect by incorporating a gun model that follows the user's cursor. I've coded a click event so that an object moves in front of the gun and follows the direction of the cursor.

My approach involves using setAttribute and requestAnimationFrame:

renderObj: function(obj){
        window.requestAnimationFrame(function() {
        renderObj(obj);
        });
    }

This setup helps create the animation of the bullet moving in a specified direction.

However, I'm encountering issues when I attempt to retrieve the object's location after it has been set with setAttribute. Here is how I tried to get the location:

var objWorldPos = new THREE.Vector3();
objWorldPos.setFromMatrixPosition(obj.object3D.matrixWorld);

When I change the position using setAttribute, I update the attribute in the bullet tag with obj.attributes.position="x y z";. I'm aware this might not be the optimal approach, and I'm wondering if there's a way to set the element's position using three.js and retrieve it using

THREE.Vector3()'s object3D.matrixWorld
method...

Any assistance on this matter would be greatly appreciated. Thank you!

Answer №1

Personally, I prefer not to mix the process of locating objects in three.js and a-frame. When I set the position in three.js using object3D.position.set(), I am unable to retrieve it using the getAttribute('position') method.
You can set the location by using the following methods:

el.object3D.position.x = 5;
//OR
el.object3D.position.set(5,4,0);
//OR BY THE WORLD MATRIX AS 
var matrix = new THREE.Matrix4();
matrix.set(11,12,13,14,
           21,22,23,24,
           31,32,33,34,
           41,42,43,44);
el.object3D.applyMatrix(matrix);
//RETRIEVE THE LOCATION:
console.log(el.object3D.position.x);
console.log(el.object3D.position);
console.log(el.object3D.matrixWorld);

In this context, the Matrix4 serves as the transformation matrix. You can find detailed information in the three.js documentation, as well as the a-frame documentation.


ngoKevin has achieved a similar goal by:

1) Obtaining the gun position using the matrixWorld

var matrixWorld = gunEl.object3D.matrixWorld;
position.setFromMatrixPosition(matrixWorld);
bulletEl.setAttribute('position', position);

2) Setting the bullet rotation:

var rotation = gunEl.getAttribute('rotation');
bulletRotation = bulletEl.getComputedAttribute('rotation');
  bulletEl.setAttribute('rotation', {
    x: bulletRotation.x + rotation.x,
    y: bulletRotation.y + rotation.y,
    z: bulletRotation.z + rotation.z
  });
});

Then, add the bullet using the appendChild() method and make it move on tick()

Feel free to explore the project, as it can greatly assist you in achieving your goals.

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

Is there anything else I should attempt in order to fix this npm start error?

I have been troubleshooting this issue by researching other stack overflow posts, but I continue to encounter the same error message repeatedly. My goal is to execute a Javascript program that incorporates ReactJS. Initially, everything was functioning sm ...

flexible side-by-side alignment - adaptable grids

I am currently working on a website project that involves a ul list with responsive columns. The column width adjusts based on the window size, and I aim to center-align the text within the li element according to the new column width. If you want to view ...

Can you please guide me on how to effectively configure a personalized time zone using MUI date picker combined with dayjs?

In my application, the user's time zone is supplied by the server instead of being determined by the browser's settings. When I receive a Unix timestamp from the server and pass it to the date picker, the displayed date is incorrect because the ...

Users are reporting a problem with the PrimeNG confirmation dialog where it becomes unresponsive and locks up the screen

Previously functioning code seems to have been affected by an update to PrimeNG. The confirmation dialog that was once usable is now hidden behind a gray click-mask, rendering everything on the screen unclickable: https://i.sstatic.net/YN7Iu.png The HTML ...

Three.js: Spherical boundary of an object that has been resized

When working with a collection of 3D shapes such as pyramids, cubes, octahedrons, and prisms, I encountered an issue with building described spheres around them. While it's straightforward to create the spheres using geometry.boundingSphere due to its ...

Setting the value for datepicker and timepicker in ReactJS for individual rows

Can you please explain how to set a default value for the datepicker and timepicker in each row? I have successfully implemented the datepicker and timepicker functionalities in my code. In the home.js file, there is a state called additionalFields which ...

Access AWS Lambda environment variables in Node.js using webpack

Looking to access environment variables in Node.js with Webpack? When trying to access them using process.env null values are returned. ...

What could be the reason for the electron defaultPath failing to open the specified directory?

Hi, I'm experiencing difficulties opening the directory path (/home/userxyz/Releases/alpha) using electron. This is what I have attempted: I have a similar path on Ubuntu: /home/userxyz/Releases/alpha When trying to access this path with the fo ...

render target in three.js EffectComposer

When we utilize an EffectComposer, the scene is rendered into either composer.renderTarget2 or composer.renderTarget1. In a particular example, I came across this: renderer.render( scene, camera, composer.renderTarget2, true ); renderer.shadowMapEnabled ...

Updating the light and OrbitControls in three.js

I am currently utilizing threejs to showcase an object and using OrbitControls to manage the movement of the scene with my mouse. Additionally, my scene features a DirectionalLight. Initially, when the scene is rendered, the DirectionalLight illuminates m ...

What could be causing this jQuery to malfunction?

Having trouble with the functionality of hasclass and this.addclass. if ($('.sidebar-menu-container li').hasClass('current-menu-item')) { $(this).addClass('expanded'); } Check out this CodePen for reference. ...

The Query.formatError message indicates that there is an issue with the 'users.email' column in the where clause of the database query

I'm having some trouble with a piece of code. Here's my signup function : exports.signup = (req, res) => { // Adding User to Database console.log("Processing func -> SignUp"); User.create({ name: req.body.name, username: req.body. ...

Exploring the implementation of method decorators that instantiate objects within Typescript

Currently, I have been working on a lambda project and utilizing the lambda-api package for development. As part of this process, I have implemented decorators named Get and Post to facilitate mapping routes within the lambda api object. These decorators e ...

Adjust the appearance of input fields that exclusively have the value "1"

When designing my website, I encountered a problem with the style I chose where the number "1" looks like a large "I" or a small "L." I am wondering if there is a way to use JavaScript to dynamically change the font style for input fields that only contai ...

Is it possible to exclusively focus on the specified data attributes?

Is there a method to specifically target the 'data-season' attribute with the value "winter"? This is my HTML: <li data-season="summer">summer <ul class="groups"> <li data-item="beach">beach</li> <li data-item ...

What is the best way to export assets into a React Native JS file?

After watching a video on YouTube, I noticed that at 3:20 the individual in the video quickly exported multiple assets into a file without providing any explanation. Can someone please view this specific moment in the video and clarify how this person mana ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

I am having trouble figuring out the issue with the state and how to properly implement it in Typescript

I am having difficulties sending emails using Nodemailer, TypeScript, and NextJS. The contact.tsx file within the state component is causing errors when using setform. As a beginner in TypeScript, I have been unable to find a solution to this issue. Any he ...

Overwriting Resolved Data in Angular UI-Router Child States

I'm facing an issue where the resolve function is the same in both parent and child states, but I need it to return different values based on the child state. Instead of customizing the implementation for each state, it seems to be inheriting the beha ...

Attempting to load an image through an AJAX Request may prove to be unsuccessful

I am facing an issue with using an AJAX request to load a gif image from the following source: Despite my attempts, using the response on the image source like this: $('#cat-thumb-1').attr('src', 'data:image/gif;base64,' + d ...