Tips for eliminating corner indexes from a 2D array?

Exploring forward ray tracing algorithm using Three.js. I have developed a sample using a 2D array where the Spotlight's location is parsed, but not directly involved.

To create lines of sight, I set:

startPoint = position of SpotLight
endPoint   = hardcoded initial value

https://i.sstatic.net/BdU4o.png

Next, I implemented a nested loop (17x17) to generate a ray in each iteration as shown below:

forward_RT(){

    //Declare the start and end points of the first ray (startPoint remains constant)
    var f_ray_startPoint = new THREE.Vector3(spotLight.position.x, spotLight.position.y, spotLight.position.z);
    var f_ray_endPoint = new THREE.Vector3(-490, 0, 495); //Initially hard-coded for ray endPoint

    //Define ray materials
    var ray_material_red = new THREE.LineBasicMaterial( { color: 0xff0000, opacity: 10} );
    var ray_material_yellow = new THREE.LineBasicMaterial( { color: 0xffff00 } );
    var ray_material_green = new THREE.LineBasicMaterial( { color: 0x00ff00 } );

    //Set up ray geometry
    var ray_geometry = new THREE.Geometry();
    ray_geometry.vertices.push( f_ray_startPoint );
    ray_geometry.vertices.push( f_ray_endPoint );

    //Initialize values for 2D array grid
    var rows = 17;
    var cols = 17;
    var rayOffset = 60; //Offset for every X iteration

    for(var x=0; x<rows; x++){
        for(var z=0; z<cols; z++){
            //Create a ray
            var f_ray = new THREE.Line(ray_geometry.clone(), ray_material_red);
            f_ray.geometry.vertices[1].x = f_ray_endPoint.x;

            scene_Main.add(f_ray); //Add ray to the scene
            f_ray_endPoint.x += rayOffset; //Increment offset for new rays

            if(f_ray_endPoint.x >= 490){
                f_ray_endPoint.x -= (cols * rayOffset);
            }
        }
        f_ray_endPoint.z -= rayOffset;
    }
}

For those interested in graphics, note that opacity does not function correctly on the material of the Three.Line.

Is there a way to enable transparency for the line?


Main Query

How can I restrict the iteration so that the rays do not extend beyond the edges of the SpotLight circle? Essentially, I want only the rays within the white circle around the SpotLights to be rendered.


Answer №1

If you are looking to create a discrete grid of X and Y rays within a circle, you can utilize the built-in method Vector2.distanceTo() in Three.js. By calculating the distance to the center of the circle and checking it against the radius, you can efficiently only render the rays within the circle:

// Define the center of your circle
var center = new THREE.Vector2(centerX, centerZ);
// Specify the radius of your circle
var radius = 17 / 2;
// Temporary vector for distance calculation per iteration
var rayEnd = new THREE.Vector2();
// Store the calculated distance
var distance = 0;

for (var x = 0; x < rows; x++) {
    for (var z = 0; z < cols; z++) {
        // Set endpoint position for this ray
        rayEnd.set(x, z);
        // Calculate distance from center
        distance = rayEnd.distanceTo(center);

        // Skip rendering if beyond circle's radius
        if (distance > radius) {
            continue;
        } else {
            // Render ray at x, z coordinates
        }
    }
}

Here are some suggestions:

  1. To enhance rendering performance, consider using a single LineSegments object instead of multiple individual Line objects.
  2. You can generate geometry around the origin (from -8 to 8), calculate distances from (0, 0), and then shift it by 60 units with position.x = 60 for simplicity.

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

I have been unable to find a solution for the non-functioning jQuery (3.4.1 / 3.3.1) load() issue

I have been working with jQuery's .load() function Take a look at my code snippet: <html> <head> <meta charset="utf-8"> <title>load demo</title> <script src="https://code.jquery.com/jquery-3.4.1.js"> ...

JavaScript: How can I remove it when I click anywhere on the webpage with onClick?

A challenge I'm facing involves creating a form with an input field that changes its border color when clicked. My goal is for the border to return to its original color when clicking anywhere else on the page. -HTML <form action=""> ...

Tips for adjusting the color of the white tick in Material UI Checkbox with React and JavaScript

I'm currently attempting to customize the default white tick (not the checkbox background!) and change it to a different color that I choose. While I have come across solutions for earlier versions of MUI and React, I am specifically looking for a sol ...

Buttons in Laravel are shifting unexpectedly

There are three buttons available with different functions. <div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary"> {{ __('update') ...

An issue occurred while deploying Docker on Railway services: Build Error

After successfully deploying my Django project on Railway, I decided to add SendGrid mail functionality using the django-sendgrid-v5 package. Everything worked fine in the development environment, including sending emails like user signups. However, when ...

Validation error occurred while attempting to send form data to the Contact Form 7 API through Next.js

Having trouble sending data to the Contact Form 7 API and encountering an error while submitting the form: {into: "#", status: "validation_failed", message: "One or more fields have an error. Please check and try again.", post ...

Sharing node_modules via Npm and ensuring the package.json is correctly mapped

I have a dilemma with two projects, one serving as a server and the other as a client. They share very similar dependencies, making it tedious to set up shared dependencies without manual file editing or installing everything twice. The issue is exacerbate ...

"Enhance your Magento store with the ability to showcase multiple configurable products on the category page, even when dropdown values are not

As I work on adding multiple configurable products to a category list page in Magento 1.7.2, I am facing some challenges due to using the Organic Internet SCP extension and EM Gala Colorswatches. While following tutorials from various sources like Inchoo a ...

How can you use jQuery to activate a specific tab?

I have 3 tabs with 3 different ids. $(document).ready(function() { $(function() { $( "#tabs" ).tabs(); }); $("#links > a").click(function() { var link = $(this).attr('href').substr(-1,1); console.log(link); $('#t ...

The div functions seem to stop working properly after they have been multiplied

Initially, I use JavaScript to multiply the div but then encounter issues with the function not working properly. function setDoorCount(count) { $('.doors').html(''); for (var i = 0; i < count; i++) { var content = " ...

Using AngularJS with the Phonegap Facebook plugin

I am looking to build a Javascript app and deploy it on Android and iOS using Phonegap. My goal is to integrate Facebook login into the app. After exploring the phonegap-facebook plugin, I was able to successfully implement the Facebook login feature. How ...

Changing the custom route in React Router to utilize a render prop instead of the component prop

I'm currently working on a React app that incorporates React Router. I've been encountering a bug in my code stemming from my custom ProtectedRoute component: const ProtectedRoute = ({ component, ...args }) => ( <Route component={with ...

Vue automatically populates an empty array with an Observer object

I have been attempting to create an empty array in the data and then fetch a JSON from the server to populate it. The issue I am encountering is that the array consistently includes an extra Observer object, so when I log it, I see: empty items array: ...

Tips for ensuring that the "this" in React ES6 static method is bound to the lexical scope

Currently in React with ES6 via babel, my goal is to develop a static method that can update the state of the Component it belongs to by accepting an object as an argument. However, I'm facing an issue where "this" is not bound to the lexical scope. ...

What is the best way to assign attributes to all items in an array, excluding the currently selected one?

I need to implement dynamic buttons in my HTML document while a JavaScript class is running and receives a response from the backend. I am using jQuery and vanilla JS, and have included an example below to demonstrate this functionality. The goal is to dis ...

What is the best way to include the application version in an Electron project using JavaScript

While attempting to publish an update for my app, I encountered a strange error. Can anyone pinpoint the issue? (Note: Node.js is included) Error Message: Unexpected token < <script> console.log(process); let output = <h2 class="page- ...

Restricting Meteor Publish to specific user (admin) for all collections

Is there a method to exclusively publish all meteor collections to users with the role of {role: "admin"}? The meteor autopublish package grants database access to all clients. Are there any techniques to utilize the autopublish package while implementing ...

The swipe function of Hammer.js is unable to detect gestures on a rotated iframe

After creating a rotated iframe on the page using CSS transforms, I attempted to implement swipe events within the iframe. body.rotate iframe { transform: rotate(90deg); transform-origin: top right; position: absolute; t ...

RegEx in JavaScript to identify and match the innerHTML property of all elements

I am currently in the process of developing a Chrome extension that needs to identify specific pages within a website, including the Log In / Sign In page, the Sign Up / Register page, the About page, and the Contact Us page. My approach involves obtainin ...

Discovering the value of an object through its prototypes

Is it possible to create a function that can locate the value "5" within an object's prototype? What is the proper algorithm to achieve this? var rex = { "Name": "rex", "Age": 16, } te = { "to": 5, } rex.te = Object.create(te); function findValu ...