Colliding with sin() and cos() animations: Meshes entwined in motion

Greetings fellow developers! I'm excited to delve into JavaScript and Three.js with all of you.

Below is the code snippet for creating 4 cubes and an arrow, resembling the image found here:

Image1

// Scene
const scene = new THREE.Scene();

// Groups
const cubes = new THREE.Group();

// Ambient Light
const light = new THREE.AmbientLight(0xffffff, 1);
scene.add(light)

// Reference Circle or Path
const circle = new THREE.CircleGeometry(5, 100)
const circlePath = new THREE.Path()
const stroke = new THREE.LineBasicMaterial({color : 'white'})
const ref = new THREE.Line(circle, stroke)
scene.add(ref)

// Mesh 
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: 'red' })
const mesh = new THREE.Mesh(geometry, material)

// Mesh 2  
const geometry2 = new THREE.BoxGeometry(1, 1, 1)
const material2 = new THREE.MeshBasicMaterial({ color: 'blue' })
const mesh2 = new THREE.Mesh(geometry2, material2)

// // Mesh 3 
const geometry3 = new THREE.BoxGeometry(1, 1, 1)
const material3 = new THREE.MeshBasicMaterial({ color: 'green' })
const mesh3 = new THREE.Mesh(geometry3, material3)

// // Mesh 4 
const geometry4 = new THREE.BoxGeometry(1, 1, 1)
const material4 = new THREE.MeshBasicMaterial({ color: 'purple' })
const mesh4 = new THREE.Mesh(geometry4, material4)

// Mesh 5 Arrow
const geometry5 = new THREE.ConeGeometry(1, 4, 3)
const material5 = new THREE.MeshBasicMaterial({ color: 'yellow' })
const arrow = new THREE.Mesh(geometry5, material5)

scene.add(mesh, mesh2, mesh3, mesh4, arrow)


const axesHelper = new THREE.AxesHelper();
scene.add(axesHelper)

// Camera

const aspect = {
    width: window.innerWidth,
    height: window.innerHeight
}

const camera = new THREE.PerspectiveCamera(75, aspect.width / aspect.height)
camera.position.x = -0.15;
camera.position.z = 10;

scene.add(camera)

// Renderer 
const canvas = document.querySelector('.draw')
const renderer = new THREE.WebGLRenderer({ canvas });
renderer.setSize(aspect.width, aspect.height)
renderer.render(scene, camera)

const clock = new THREE.Clock();

const animate = () => {
    const time = clock.getElapsedTime()
    console.log(time);
    const a = time;
    let px;
    let pz;
    let r = 5;

    px = r * Math.cos(a);
    pz = r * Math.sin(a);

    mesh.position.set(px, pz, 0);
    mesh.rotation.x = time * Math.PI * 0.1;
    mesh.rotation.y = time * Math.PI * 0.3;

    mesh2.position.set(px, pz, 0);
    mesh2.rotation.x = time * Math.PI * 0.1;
    mesh2.rotation.y = time * Math.PI * 0.3;
    
    mesh3.position.set(px2, pz, 0);
    mesh3.rotation.x = time * Math.PI * 0.1;
    mesh3.rotation.y = time * Math.PI * 0.3;

    mesh4.position.set(px, pz, 0);
    mesh4.rotation.x = time * Math.PI * 0.1;
    mesh4.rotation.y = time * Math.PI * 0.3;

    arrow.rotation.y = time * Math.PI * 0.7;

    renderer.render(scene, camera)
    window.requestAnimationFrame(animate)
}
animate();

I'm facing an issue where all my geometries overlap as seen in this image:

Image2

Do you have any suggestions on how to prevent overlapping? Perhaps implementing some sort of delay could help, but I'm not certain on how to integrate it.

Based on my understanding, creating separate loops for each cube might resolve the issue, but currently, it displays like this: Image1.

If you have any advice on introducing delays for each mesh to avoid overlap, please share your insights.

Thank you for your valuable input. :)

Answer №1

I have successfully corrected your code:

  • The typo with px2 has been rectified.
  • All objects on the circle have been repositioned using
    r * Math.cos(time + Math.PI / 2 * idx)
    and
    r * Math.sin(time + Math.PI / 2 * idx)
    .
  • Unnecessary variables have been removed for optimization purposes.
  • Code duplication has been reduced by introducing arrays and loops.

All objects now share the same position and rotation.

// Scene
const scene = new THREE.Scene();

// Ambient Light
const light = new THREE.AmbientLight(0xffffff, 1);
scene.add(light);

// Reference Circle or Path
const circle = new THREE.CircleGeometry(5, 100);
const stroke = new THREE.LineBasicMaterial({color : 'white'});
const ref = new THREE.Line(circle, stroke);
scene.add(ref);

// Meshes
const meshes = [
    new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial({ color: 'red' })),
    new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial({ color: 'blue' })),
    new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial({ color: 'green' })),
    new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial({ color: 'purple' })),
];
const arrow = new THREE.Mesh(new THREE.ConeGeometry(1, 4, 3), new THREE.MeshBasicMaterial({ color: 'yellow' }));
scene.add(...meshes, arrow);


const axesHelper = new THREE.AxesHelper();
scene.add(axesHelper);

// Camera

const aspect = {
    width: window.innerWidth,
    height: window.innerHeight
};

const camera = new THREE.PerspectiveCamera(75, aspect.width / aspect.height);
camera.position.x = -0.15;
camera.position.z = 10;

scene.add(camera);

// Renderer 
const canvas = document.querySelector('.draw');
const renderer = new THREE.WebGLRenderer({ canvas });
renderer.setSize(aspect.width, aspect.height);
renderer.render(scene, camera);

const clock = new THREE.Clock();

const animate = () => {
    const time = clock.getElapsedTime();
    console.log(time);
    let r = 5;

    meshes.forEach((mesh, idx) => {
        mesh.position.set(r * Math.cos(time + Math.PI / 2 * idx), r * Math.sin(time + Math.PI / 2 * idx), 0);
        mesh.rotation.x = time * Math.PI * 0.1;
        mesh.rotation.y = time * Math.PI * 0.3;
    });
    arrow.rotation.y = time * Math.PI * 0.7;

    renderer.render(scene, camera);
    window.requestAnimationFrame(animate);
}
animate();

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

Obtain a transformed mesh that has been displaced using a displacementMap within three.js

Seeking to extract and export the mesh affected by a displacementMap. The displacement of vertexes is determined by this line in the shader (taken from three.js/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl): transformed += normalize(obje ...

Choosing a combination of classes

For my web application, I created checkboxes that control the visibility of windows by toggling classes on elements. My JavaScript code successfully achieves this functionality. $(document).ready(function(){ $('#field').change(function(){ ...

Analyzing the values of two sets of key-value pairs

I am facing an issue where I have two sets of objects labeled LABELS1 and LABELS2, and my goal is to iterate through them. If any of the IDs from LABELS1 match any of the IDs from LABEL2, I need to update the simple_value of LABELS1 with the correspondin ...

What are the methods for differentiating between a deliberate user click and a click triggered by JavaScript?

Social media platforms like Facebook and Twitter offer buttons such as Like and Follow to allow users to easily engage with content. For example, on Mashable.com, there is a Follow button that, when clicked, automatically makes the user follow Mashable&ap ...

Validating checkboxes using HTML5

When it comes to HTML5 form validation, there are some limitations. For instance, if you have multiple groups of checkboxes and at least one checkbox in each group needs to be checked, the built-in validation may fall short. This is where I encountered an ...

Warning for pending changes prior to moving in Svelte

My current setup involves a Svelte application that includes form content. Whenever a modification is made within the form, an "unsaved change" alert can be triggered upon page refresh. However, when attempting to navigate to a different page using Svelt ...

Refresh a table using jQuery Mobile, PHP, and AJAX without having to reload the entire page by clicking a

Currently, I am working on a web app that includes a pop-up feature. When the user clicks on the pop-up to close it, I want the table data to refresh without having to reload the entire page. This pop-up allows users to modify existing data in the table. A ...

Which characters are permissible for the id attribute to prevent the jQuery selector from throwing an exception?

I am facing a situation where the id attribute is inputted by an end user. For instance, if the id for a textbox is "11_=11" as entered by the user, then the HTML code will appear like this: <input type="text" id="11_=11"> The corresponding jQuery ...

Build a unique array of identifiers extracted from an object

https://i.sstatic.net/PaFXj.png I am seeking advice on how to extract an array of IDs values by iterating through an object in React JS. https://i.sstatic.net/GV6ga.png const initialState = useMemo(()=> { return dataTable.filter(result => f ...

Ensuring that all routes in Express 4 redirect from HTTP to HTTPS

Is there a way to redirect all http:// requests to https:// for every route in my express 4 application? I've tried this method, but it seems to cause a redirect loop error I'm currently utilizing the Express 4 Router in the following manner: ...

Using Firestore startAt() with Redux: a comparison of serializable and non-serializable scenarios

I find myself at a pivotal moment in my Firebase project and am seeking some general guidance. Here are the key points as I have gathered them through my research: When it comes to Firestore queries, there is a useful feature for pagination called startAt ...

What are the steps to resolve the import error of @threlte/extras in SvelteKit?

When attempting to import @threlte/extras into my SvelteKit component, I encounter the error message "Failed to load URL three/examples/jsm/objects/GroundProjectedEnv". Despite checking the directory and confirming that the file is not there, the error p ...

What is preventing obj from being iterable?

When I try to compile this code, an error appears stating that the object is not iterable. Why is this happening? My goal is to determine the number of users currently online. let users = { Alan: { age: 27, online: false }, Jeff: { age ...

JavaScript's prototypical inheritance model allows objects to inherit properties and

Exploring javascript's prototypical inheritance and object-oriented programming is new to me. I attempted to create a base object called Account and then inherit the CheckingAccount from it. Below is my code snippet. function Account(fName, lName) { ...

What are some best practices for managing asynchronous requests on the client side with Node.js?

I am a beginner in NodeJS, currently utilizing it on the server side for my projects. My goal is to create a simple REST-based GET request that takes a search parameter called searchvar from the user and returns any matching records found in a JSON array. ...

What is the best way to pass a prop into the <router-link>?

If I replace this {{ name }}, the result is "campaigns" Now, I want to use that in my link <router-link :to="'/' + '123' + '/' + item.id"> {{ item.name }}</router-link> I attempted to substitute '1 ...

Having trouble with prettyphoto functionality

Seeking assistance as I am struggling to get this working Here is how I have set it up: <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script> <link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen"/ ...

The function findOne from Mongoose seems to be non-existent, all while utilizing the Passport library

Whenever I try to implement my local strategy using the passport lib, I keep encountering this error. TypeError: UserModel.findOne is not a function I've spent hours searching for a solution that addresses this issue but haven't been successful ...

The functionality to disable the submit button for unchecked radio buttons is not functioning properly

I am currently working on a form where I need to disable the submit button until all fields are filled out. Everything is functioning properly for other field types, EXCEPT FOR RADIO BUTTONS. Even when we do not select a radio option, the Submit button s ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...