Is the position behind the object in Three JS?

Is there a way to determine if a position is behind a 3D character and not in front or to the side? I have a 3D character with predefined positions on the floor. I have attached a rough sketch to illustrate what I am trying to achieve (apologies for the poor drawing). Essentially, I want to identify and return the positions of the red circles within the red lines, excluding any circles outside of these boundaries.

https://i.sstatic.net/3BG73.png

Is it possible to accomplish this? If so, can you provide any suggestions on how to do so? I am unsure which functions to use from Three JS for this specific task, or if it is even feasible.

Thank you!

Answer №1

Absolutely, it can be done.

To start, you need to check if a point or circle is positioned behind the player. This involves calculating the dot product between the unit vector representing the direction the player is facing and the unit vector pointing to the circle. If the dot product value is less than or equal to 0, then the circle is considered to be behind the player.

(A unit vector is a vector with a magnitude of one, ensuring its x/y/z components do not exceed 1)

Here's a code example:

// Assume this code is inside a loop
const directionVect = circle.position.clone().sub(player.position).normalize();

const playerFacing = player.getWorldDirection(new THREE.Vector3());

if (playerFacing.dot(directionVect) <= 0) {
    // Circle is behind the player
    // ...continue handling logic here...
} else {
    return;
}

Once you have identified the circles behind the player, you can further determine which circles are within a specified cone angle. This involves calculating the angle between the player's position and the circle's position, then checking if it meets certain criteria (e.g., angle less than 45 degrees from the player's back).

// ...

if (playerFacing.dot(directionVect) <= 0) {
    // Circle is behind the player
    const angle = player.position.angleTo(circle.position);
    
    if (angle < Math.PI * 0.25) {
        // Perform actions with circle
    }
} else {
    return;
}

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

What methods do publications use to manage HTML5 banner advertisements?

We are working on creating animated ads with 4 distinct frames for online magazines. The magazines have strict size limits - one is 40k and the other is 50k. However, when I made an animated GIF in Photoshop under the size limit, the image quality suffered ...

The functionality of Javascript stops working once an ajax call is made

My attempt to make an Ajax call to fetch additional data upon clicking a button was successful on the first click. However, subsequent clicks on the button do not trigger the action, and the data retrieved does not apply any JavaScript functionalities like ...

Generate visual representations of data sorted by category using AngularJS components

I am facing an unusual issue with Highcharts and Angularjs 1.6 integration. I have implemented components to display graphs based on the chart type. Below is an example of the JSON data structure: "Widgets":[ { "Id":1, "description":"Tes ...

Tips for setting up a blog using nodejs and express.js

Hello everyone, I could really use some assistance. I am trying to figure out how to set up a blog using NodeJS specifically with ExpressJS, including basic functions like deleting, adding, and removing posts and comments, as well as standard authenticati ...

Combining Mocha, BlanketJS, and RequireJS has resulted in the error message "No method 'reporter'."

While using Mocha with RequireJS, my tests are running smoothly. However, I encountered an issue when trying to incorporate blanket code coverage. The error Uncaught TypeError: Object #<HTMLDivElement> has no method 'reporter' keeps popping ...

blur event triggered on a cell within a table

Currently, I am using the code snippet below to populate data using a data table. My goal is to be able to edit the data in one of the columns and then validate the value after editing using the onblur event. I attempted to call the onblur event on the t ...

Initiating PHP outcomes with the integration of JQUERY and Bootstrap

Currently, I am working on a Twitter search functionality that allows me to search for any content on Twitter. While the feature is functional, I am facing some challenges with displaying the results in the desired format. Ideally, I would like the results ...

Generating a basic PHP Request

I am a beginner in PHP and I am attempting to create a basic server using GET and POST request methods. The PHP server should simply receive JSON data and save it (POST) and then return it to the user (GET). However, for starters, I am trying this: PHP ...

Error: Attempting to access a property 'notesObjectInService' that is undefined on the object

I'm currently facing an issue where my controller is unable to load an object from a service called notesFactory. The console.log(typeof notesFactory) statement returns 'undefined', causing notesObjectInService to trigger an exception. Desp ...

Showing the total quantity of products, reminiscent of a virtual shopping basket

I am trying to show a number similar to how a shopping cart displays items. The php code I was given currently shows a cookie value, which is mostly functional. However, if you encounter errors while adding items to the cart, it increases the cookie count ...

Encountered a JavaScript error while using Internet Explorer

My web and Jquery plugins are working flawlessly on various browsers such as Firefox, Chrome, Safari (Windows & OSX), and Android. However, they encounter issues with Windows and Internet Explorer as some JavaScript fails to load. It's frustrating tha ...

Issue with jQuery: Function not triggered by value selection in dynamically created select boxes

I am in need of some assistance with my code that dynamically generates select drop down menus. I want each menu to trigger a different function when an option is selected using the "onchange" event, but I am struggling to implement this feature. Any hel ...

Tips for utilizing the "get" method in React to submit a form

Is there a way to submit a form using the "get" method to an external URL in react? Similar to how it is done in HTML like in this example: https://www.example.com/form But instead, to a third party URL...? Can I achieve something like this? The goal is ...

Using framer-motion with Next.JS ensures that content remains consistent during navigation

I added a Link on my homepage that connects to the About Us page: <Link href="/about"><a>About us</a></Link> In my _app.js file, there is an AnimatePresence wrapper: <AnimatePresence exitBeforeEnter> <Component {...p ...

Is there a way to retrieve data from a sealed JSON object using JavaScript?

The data is being fetched from the API and here is the response object: { "abc": [{ "xyz": "INFO 1", "pqr": "INFO 2" }, { "xyz": "INFO 3", "pqr": "INFO 4" } ] } We are lookin ...

Tips to center a circular progress bar in Material UI

Does anyone know how to properly center-align a circular progress bar in a login form using material UI? I'm having trouble with it not being positioned correctly: screenshot {isLoading && <CircularProgress />} {user?.ema ...

Manipulate the presence of THREE.Points in a three.r84 scene by adding or removing them

I recently upgraded from three.js version 71 to version 84 and encountered a problem with updating points in the scene. Previously, with THREE.PointCloud, it was simple to add and remove points as needed like so: function updatePoints(newData) { geom ...

Scrolling animations tailored to the navbar using jQuery

My fixed header contains a few links, and I've written some code that almost works perfectly. The issue is that there's a delay when the second function is executed. While it successfully scrolls to the top of the page when the linked element is ...

How come the behavior of Array.prototype.push() results in creating an endlessly nested array when used on itself?

While testing out the following code: const animals = ['pigs', 'goats', 'sheep']; animals.push(animals) console.log(animals); An error occurred in my testing environment: Issue: Maximum call stack size exceeded. What is c ...

Unable to display modal pop-up in ASP.NET Core MVC web application

I have developed a web application using ASP.NET CORE MVC. I encountered an unusual issue while trying to display a modal popup using JQuery. The div structure I am working with is as follows: <div class="modal fade" tabindex="-1" r ...