Moving a Ball Back and Forth Using Three.js

I’m looking to create a continuous motion for a Ball in Three.js, where it moves to the right, returns to its starting position, and then repeats the sequence.

var geometry = new THREE.SphereGeometry( 5, 32, 32);
var material = new THREE.MeshPhongMaterial( {specular: "#fdfb57", 
color: "#d8d613", emissive: "#6b6a0d", side: THREE.DoubleSide} );
var ball = new THREE.Mesh(geometry, material);

var render = function () {
    requestAnimationFrame( render );
    renderer.render(scene, camera);
    renderer.setSize(window.innerWidth, window.innerHeight);

// I'm unsure how to code the movement of the ball. Can you help?
};

render();   

How can I go about implementing the movement of the ball as described?

Answer №1

To achieve the desired animation effect, you can either manually update the ball.position at every frame or employ a tool such as Tween.js to generate a motion path between the two specified points.

If you're aiming for a straightforward left-to-right repeating animation, simply adjusting the position will suffice.

Experiment with this code snippet on avgp.github.io/h2g2three:

var geometry = new THREE.SphereGeometry( 5, 32, 32);
var material = new THREE.MeshPhongMaterial( {specular: "#fdfb57", color: "#d8d613", emissive: "#6b6a0d", side: THREE.DoubleSide} );
var ball = new THREE.Mesh(geometry, material);
var dxPerFrame = 1; // movement increment per frame

scene.add(ball);

onRender = function() {
  ball.position.x += dxPerFrame; // move the ball
  if(ball.position.x > 100) dxPerFrame = -1; // adjust direction if too far right
  if(ball.position.x < -100) dxPerFrame = 1; // alter direction if too far left
};

// Press Alt+Return to execute the code

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

Link the Sass variable to Vue props

When working on creating reusable components in Vue.js, I often utilize Sass variables for maintaining consistency in colors, sizes, and other styles. However, I recently encountered an issue with passing Sass variables using props in Vue.js. If I directly ...

Switching Story Tense on Facebook Open Graph

After creating a unique story for my facebook app, I discovered that when making a basic story post using the facebook js sdk, the resulting post is in past tense and depicts the object in singular form. For example, instead of saying: John is eating an a ...

Create a single declaration in which you can assign values to multiple const variables

As a newcomer to react/JS, I have a question that may seem basic: I need multiple variables that are determined by a system variable. These variables should remain constant for each instance. Currently, my approach is functional but it feels incorrect to ...

What could be causing the API link to not update properly when using Angular binding within the ngOnInit method?

Hi there, I'm currently working on binding some data using onclick events. I am able to confirm that the data binding is functioning properly as I have included interpolation in the HTML to display the updated value. However, my challenge lies in upd ...

Guide to highlighting rows in v-data-table with a click in Vuetify (version >= 2.0)

In my email management system, I utilize a v-data-table to organize emails. When a user clicks on a row, a popup displaying the email details appears. Desired Feature: I am looking to have the rows marked as "readed" (either bold or not bold) after th ...

Node.js console and endpoint are returning an object, but the JSON object cannot be fetched

Currently, I am working on a project for an online course where I am utilizing an NLP sentiment analysis API. Although I have made significant progress, I seem to be stuck at the final step. When I send the URL for analysis via the API call, I can see the ...

Identifying Errors in Meteor's Data Publications

I am currently working on a web application using Meteor and AngularJS 2. Take a look at the publication function below: Meteor.publish('abc', function () { // For throwing the meteor error according to the condition if(!this.userId) throw new ...

Associating mongoose object with a DTO object in an Express.js application

I am looking for a way to transform mongoose result objects into DTOs for my views. Here is an example query that returns a mongoose object: const returnedData = (err, result) => { //Result object is a schema from Moongose cb(err, re ...

Including material-ui/core/Table produces a data error before it has even been connected

My Initial Redux Saga Setup In my Redux Saga code, I have a generator function that fetches data from a mock API: function* fetchPickingScans({orderReference}){ try{ const response = yield call( scanningMockApi.getPickingScans, orderReference ...

Assigning numerical ratings to a web-based questionnaire in HTML

In my questionnaire, I have radio buttons and checkboxes that need to be graded. The format of the input elements looks like this: <input type="radio" name="1" value="Yes" onclick="document.getElementById('pls').setAttribute('requi ...

Attempting to activate an ASP button that is created within a gridview after pressing the enter key within a textbox

I am currently working on a gridview with dynamically generated rows, each row containing text boxes and buttons. The goal is to update the database with values from the textboxes when UpdateBtn1 is clicked. Users should be able to either click the button ...

Is there a way to use flexbox in a grid to center only a specific tab from MUI?

I am working with an array of tabs and encountering a layout issue. The tabs need to share the available space when there's more than one tab, but when there's only one tab, it should be positioned in the middle of the column. How can I address t ...

Converting JavaScript code to jQuery and integrating it into a WordPress website has become a common practice

I recently developed a working javascript function as shown below: function calc(A,B,SUM) { var one = Number(A); var two = Number(document.getElementById(B).value); if (isNaN(one)) { alert('Invalid entry: '+A); one=0; } if (isNaN(tw ...

Displaying a Next.js component depending on the environment setting

Having trouble displaying a maintenance message to users based on an environment value. In my .env.local file, I have the following value set: NEXT_PUBLIC_SHOW_MAINTENANCE=true This is how my page is structured: const Index = () => { const showMai ...

Guide on centering an unfamiliar element in the viewport using HTML, CSS, and JavaScript

In the process of developing my VueJS project, I have successfully implemented a series of cards on the page. However, I am now facing a challenge - when a user selects one of these cards, I want it to move to the center of the screen while maintaining its ...

Issue with Web Worker functionality in SvelteKit on Firefox version 106.0.5

I've set up a function in my main file like this: const loadWorker = async () => { const SyncWorker = await import("$lib/canvas.worker?worker"); syncWorker = new SyncWorker.default(); syncWorker?.postMessage({}); ...

How can I manipulate JSON animation using Three.js?

I utilized this code to import a JSON animation from Blender: var loader = new THREE.JSONLoader(); loader.load( 'monster2.json', function ( geometry, materials ) { var material = materials[ 0 ]; material.morphTargets = true; ...

Implementing $modal.open functionality in AngularJS controller using Ui-Bootstrap 0.10.0

Is there a way to properly call $modal.open from the controller in AngularJS since the removal of the dialog feature in ui-bootstrap 0.1.0? What is the alternative method available in the current version? In previous versions like 0.1.0, it was simply don ...

executing jQuery toggle on freshly generated content

I have a webpage that I designed using jQuery. Within this page, there is a table with rows assigned specific color classnames (e.g., tr class="yellowclass"). Users can filter the rows by clicking checkboxes to show/hide tables of different colors. The i ...

Explore how to set up Express with React without resorting to using create-react

I am familiar with the react and Node.js Express bundle, but I require assistance. While this question may have been posed by someone else before, I have not come across a similar query within the same framework. The specific question is: How can queries ...