Generating a three-dimensional sphere from flat coordinates with the help of sine and cosine functions

I am trying to achieve mapping a set of 2D coordinates to a 3D surface of a sphere. To accomplish this, I am starting with an array of xy coordinates.

Using the following loops, I am generating 20*20 xy coordinates ranging from 0 to 1 on each axis:

var plot = []

for (var i = 0; i <= 20; i++) {
for (var ii = 0; ii <= 20; ii++) {
    plot.push({
        x: ii/20,
        y: i/20
    })
}
}

Then, I am converting the xy values to xyz values by iterating through the array:

for (var i = 0; i < plot.length; i++) {
points.push({
    x: Math.sin(plot[i].x*(6.283185307)) * Math.sin(plot[i].y * Math.PI),
    y: plot[i].y * 2,
    z: Math.cos(plot[i].x*(6.283185307)) * Math.sin(plot[i].y * Math.PI)

});
}

I am facing two issues:

  • I have to use 6.2831.. because Math.sin(Math.PI*2) doesn't return 0

  • The resulting sphere appears distorted along the y axis:

https://i.sstatic.net/7GA9O.png

Answer №1

The pattern you're seeing is the result of a half sine wave rotating around the y axis, creating a shape with a horizontal radius determined by sin(y*pi/2) for y in 0..2. This causes the ends of the shape to point towards the north and south poles.


To calculate the coordinates, use u=plot[i].x * 2*Math.PI and v=plot[i].y * Math.PI

x : sin(u)*sin(v)
y : cos(v)
z : cos(u)*sin(v)

These equations will give you points on the unit sphere. Your worry about Math.sin(Math.PI*2) is unnecessary. In reality, Math.sin(6.283185307) would be farther from zero, as it is a less accurate approximation of 2*pi. (This is confirmed by the values in the comment by Tomasz Jakub Rup.)

Answer №2

Ensuring precise point matching is crucial in certain applications. For example, when constructing a boundary-less mesh of the sphere, special attention must be given to the boundary points.

for (var i = 0; i <= 20; i++) {
    for (var ii = 0; ii <= 20; ii++) {
        theta = 2* Math.PI * i /20;
        phi = Math.PI * ii / 20;

        if(ii==0)   // North Pole
            points.push( {x:0; y:1, z:0} )
        else if(ii==20)   // South Pole
            points.push( {x:0; y:-1, z:0} )
        else if(i== 0 || i == 20) // 0º longitude
            points.push({ x: 0,
                y: Math.cos(phi),
                z: Math.sin(phi) } )
        else
            points.push({ x: Math.sin(theta) * Math.sin(phi),
                y: Math.cos(phi),
                z: Math.cos(theta) * Math.sin(phi) });
     }
}

In scenarios where exact coordinates are of utmost importance, additional cases for the equator and longitudes like 90º, 180º, 270º could be beneficial.

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

Ajax fails to transfer the complete data

I am currently facing an issue with my request. Here is the code snippet that I need help with: logInWithFacebook = function() { FB.login(function(response) { if (response.authResponse) { FB.api('/me', {fields: 'name,email,location,p ...

Guide to deploying a React application using Material-UI and react-router

I've successfully built an application using React, Material-UI, and react-router. Below is the content of my complete package.json: { "name": "trader-ui", "version": "0.1.0", "private": true, "dependencies": { "@material-ui/core": "^3.2. ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

The event.target.x attribute on the <i /> tag element

In my code, there is an <i name="documentId" onClick={this.openDocument}/> element with the onClick method defined as follows: openDocument(event) { const { name } = event.target; console.log('name', name); console.log('target&a ...

Enhancing leaflet popup functionality by incorporating ng-click into the onEachFeature function

After creating a map and connecting it with my geojson api, I encountered an issue when trying to link each marker popup with ng-click. Simply adding HTML like this did not work as expected: layer.bindPopup("<button ng-click='()'>+feature. ...

What steps should I take to resolve the "You do not have authorization to access this directory or page" error in Azure App Services?

Currently, I am attempting to deploy my Next.js 13 application to AppServices using Github Actions. The compilation process on Github was successful, however, I am encountering an issue where my application does not seem to be deploying or starting up prop ...

Struggling to insert a JavaScript variable into a MySQL database table using PHP and AJAX

As a newcomer to these technologies, I've been struggling all day with what I expected to be a simple task. My goal is to pass a parameter from a JS function to my PHP code using AJAX and then insert that parameter into my database. Here's the J ...

Filtering dynamically generated table rows using Jquery

I'm currently working on a project that involves filtering a dynamic table based on user input in a search bar. The table contains information such as name, surname, phone, and address of users. Using jQuery, I have created a form that dynamically ad ...

Tips for adding a string variable to a JQuery HTML element attribute

Hi there, I've been working on a JQuery code to append data to a div element and it's been successful so far. Here is the code: $('#conversation').append('<div id="receiver"><p><b>' + username + ':< ...

Ways to access information from a SQLite database using Angular

I am a beginner in front-end/back-end communication and I need guidance on how to retrieve data from a SQLite db file to populate a page in my Angular project. I have no idea where to begin, so any resources you can recommend would be greatly appreciated. ...

Viewing Server Logs in a Discord Channel

My gaming server stores logs in .txt format, and I'm looking for a way to automatically send updates to a Discord channel whenever there is new log data. I am currently developing a Discord bot using Node.js. Does anyone have any suggestions on how I ...

Jasmine - effectively mimicking an object that utilizes a constructor

Currently, I am attempting to simulate the native WebSocket in a jasmine test for Angular. I have successfully spied on the constructor and `send` function, but I am struggling to figure out how to fake a call of `onmessage`. The WebSocket has been extrac ...

Issue with scroll down button functionality not functioning as expected

Is there a way to create a simple scroll down button that smoothly takes you to a specific section on the page? I've tried numerous buttons, jQuery, and JavaScript methods, but for some reason, it's not working as expected. The link is set up co ...

Any recommendations for building HTML in an iOS UIWebView?

When using a UIWeb view, how can I create HTML content? For example, I have some header html code. Then, I would like to include a JavaScript script and pass data to it. Once the JavaScript is injected, I want to add the remaining HTML content from a .html ...

JSON input in react.js sadly ended abruptly

I am encountering a problem when I attempt to submit the form. Unhandled Rejection (SyntaxError): Unexpected end of JSON input Whenever I press the submit button, this error occurs, here is the code snippet: onButtonSubmit = () => { this.setState({ ...

What is the best way to update setState when triggering an onChange event?

Here is the code snippet for a React component that handles cryptocurrency selection: import React, { Component } from 'react'; import { Select } from 'antd'; import { connect } from "react-redux"; class SelecionarCrypto extends Compo ...

Submitting Files to the API using Vue.js

I have the following code in Vue.js and I am trying to upload a file, but my issue is that I want to save the filename of the uploaded file to the JSON API using a POST method. Is there a way to achieve this? Thank you in advance. <div class="input-f ...

Tips for choosing a single row in a table using a checkbox

I need help with a table that has multiple rows and four columns. One column is for checkboxes, while the other three are select boxes set to read-only. I want users to be able to edit only one row at a time by checking the checkbox in the first column. If ...

`Launch link in new browser window`

Seeking assistance with a coding issue. I'm attempting to have links open in a new tab, but I haven't been successful using the href attribute. Below is the code snippet from src/utils/menu.js: const menu = [ { name: 'App& ...

JavaScript popup menu with a redirect URL

I utilized Tinybox from this source for launching a popup webpage. I am hoping that when I click the links on the webpage, the popup will close itself and redirect to the link's URL. Here are my JavaScript and HTML codes: <script type="text/java ...