How can I find out the direction in which my mesh is facing using three.js?

I am currently working on a project to develop a simple game that involves shooting projectiles out of a gun barrel. At the moment, I have a basic setup where a cube and a cylinder are combined as the barrel. When I rotate the group containing these elements, the barrel moves accordingly in different directions without any issues.

However, my main challenge lies in determining the exact direction in which the gun barrel is pointing. I need to accurately identify the face of the cube to which the barrel is attached, as well as its orientation in relation to the 3D space - whether it's facing X+, Y+, Z+, X-, Y-, or Z-. Apologies for any misuse of technical terms in my description. Unfortunately, none of my attempted solutions have been successful so far, hence why I haven't included them here.

If you'd like to see an example of what I'm trying to achieve, please visit this CodePen link.

Additionally, here is some code snippet related to my project just to provide more context:

var geometry = new THREE.BoxGeometry( 50, 50, 50 );
var material = new THREE.MeshNormalMaterial();
var cube = new THREE.Mesh( geometry, material );
    var cylgeo = new THREE.CylinderGeometry( 10, 5, 100, 32 );
        var cylmesh = new THREE.Mesh( cylgeo, material );

        cylmesh.rotateZ(Math.PI/2);
        cylmesh.translateY(35);


var group = new THREE.Group();

group.add( cube );
group.add( cylmesh );

scene.add(group);

Answer №1

To begin, ensure your "gun" is aligned so that the barrel faces upwards along the positive-z axis by adjusting your code in the following manner:

cylmesh.rotateX( Math.PI / 2 );

Include a visual aid in your scene to assist in understanding your setup:

scene.add( new THREE.AxisHelper( 100 ) );

In this setup, when the parent group remains unrotated, the gun barrel will point towards the positive-z axis.

If the parent group undergoes rotation, you can determine the direction in which the group (and subsequently the barrel) is facing using the following approach:

var vector = new THREE.Vector3(); // instantiate once and reuse
...
group.getWorldDirection( vector );

The outcome stored in vector will be a normalized vector pointing in the same direction as the barrel.

Implemented with three.js r.75

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

summoning the iframe from a separate window

In my current setup, I have a link that passes a source to an iframe: <a href='new.mp4' target='showVideo'></a> <iframe src='sample.jpg' name='showVideo' ></iframe> However, what I would lik ...

Is it possible to categorize elements for focus and onblur events?

In my search feature, I have implemented an autocomplete div that appears when the user types in a search field. The issue I am facing is that I want the div to disappear when the user clicks outside of it. Here is what I have attempted: //SHOW THE DIV WH ...

Using Angular.js to fetch information from a MySQL database

I'm currently trying to retrieve data from a MySQL database in an Angular.js application. I have gone through multiple tutorials, but unfortunately, none of them have been successful for me. I have a PHP script that returns a JSON array with example ...

Enhancing OpenSeadragon images with custom overlays and managing error messages

Currently, I am experimenting with the Basic Single-Row Tile Source Collection example using the same configurations and tile sources outlined in the example. However, I am encountering difficulties in adding overlays to the first and second images as int ...

The useRouter() function doesn't seem to be successfully navigating to the main landing page

"use client" import { useState } from 'react'; import {auth} from '../../firebase-config' import {createUserWithEmailAndPassword} from 'firebase/auth' import { useRouter } from 'next/router'; const SignUp = ...

fa icons moving the elements aside

I'm attempting to design a navigation menu with tabs, but I'm facing an issue where the tabs containing "fa icons" are consuming too much space, causing other elements to be shifted to the right or below (if there were more lines). How can I pre ...

How to bypass validation for required input in jQuery validate plugin

As an example, consider the <input name="surname" id="surname" type="text">. Sometimes I want to hide this input and make it non-required. My current workaround is to set a value such as "some value" when hiding the input, and then remove this value ...

Quantities with decimal points and units can be either negative or positive

I need a specialized input field that only accepts negative or positive values with decimals, followed by predefined units stored in an array. Examples of accepted values include: var inputValue = "150px"; <---- This could be anything (from the input) ...

Tips for submitting an AJAX response using a form

Steps Taken I have implemented an ajax call to retrieve checkboxes as follows: <script> $(document).ready(function(){ $("#place").change(function(){ var id = $(this).val(); alert(id); $.ajax({ ...

Guide on redirecting a webpage post form validation in JavaScript

I have a question about my JavaScript code. Even if validation fails, the contact us page still appears. How can I fix this issue? Appreciate any help. Thank you! (function () { window.addEventListener('load', function () { var forms = do ...

Discovering elements that are currently visible in an Angular list

Suppose there is a variable named users which represents an array We have the following ng-repeat statement: ng-repeat="user in users | filterUser: searchUser: assignedUsers: selectedDivision" After filtering the users using searchUser and selectedDivis ...

What is the best way to create a reusable component for a dialog box or modal window?

I have been working on developing a reusable dialog component with a yes or no button at the bottom. The main idea behind this is to create a user confirmation dialog that prompts the user to confirm their entered information before proceeding. import Re ...

Rewriting Next.js with custom headers

My web app allows users to create their own profiles with custom usernames, which can be accessed via the following URLs. ourplatform.com/john ourplatform.com/john/about ourplatform.com/john/contact ourplatform.com/jane ourplatform.com/jane/about ourplatf ...

The absence of a React JS button on the page

I'm in the process of creating a React demo application and I've come across this component: var MediaList = React.createClass({ displayName: 'MediaList', getInitialState: function() { return { tweets: getTweets(numTweets) ...

Transforming a JavaScript JSON object into a string representation

Currently in the process of constructing a website utilizing Tornado Websocket, and I've come to understand that Tornado Websocket only accepts a specific type of json format: {"key1":1,"key2":2,"key3":3} The goal is to fill element attributes with ...

How can I retrieve the decimal x and y coordinates when the mouse is moved in Typescript Angular?

I am in the process of transitioning my user interface from Flash/Flex, where it stores values in decimal format. I need to access and reuse these values. Here is a demo showcasing my problem. Here is a snippet: import { Component, Input } from '@an ...

Custom page tracking URLs cannot be generated for external links when using the Universal Analytics Code

My website is equipped with Universal Analytics code, which is added to all pages: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createE ...

What could be causing json_decode to return NULL in this scenario?

I have a custom array that I've created with the following structure: [{ "assetPreviewUrl":"pic1.jpg", "assetUrl":"pic2.jpg" }, { "assetPreviewUrl":"pic3.jpg", "assetUrl":"pic4.jpg" }] My approach involves stringifying this array and ...

Problem with Resource Query

My angular.js application includes a productsCtrl.js file that displays the following controller: app.controller('ProductsCtrl', ['$scope', 'Api', function($scope, Api) { $scope.products = Api.Product.query(); //De ...

Using Array Data Format to Customize Color in Highcharts Funnel Chart

I have included the funnel visualization code that I've been working on. $(function() { var dataEx = [ ['1 Visit', 352000], ['2 Visits', 88000], ['3+ Visits', 42000] ], len = dataEx.length, ...