Learning how to rotate a cube mid-air with three.js

Currently, I am utilizing the three.js framework along with physi.js for implementing forces and gravity in my project. The issue I am encountering involves positioning a dice on a plane and then being able to launch or flip it from that position with a specific angle by clicking on it. My goal is to have the dice rotate in the air and then land on the plane due to the force of gravity. I am familiar with the onclick event method, however, I am unsure of how to configure the dice to jump to a certain height at a 90-degree angle and rotate at a specific angle when clicked just once.

If you have any suggestions or recommendations on how I can achieve this, please provide me with the necessary steps to set up the dice accordingly. Thank you.

Answer №1

I haven't had any experience with physi.js; I usually use cannon.js for physics. However, I do have some knowledge about physics. I can explain how it's done, although I don't have an example ready at the moment. To begin, you need to cast a ray from the camera to the dice to determine if the object is clicked on. Then, you apply a force to the location where the object is clicked. I hope this information is helpful.

EDIT/Follow up: Upon reviewing physi.js, I noticed that it bears a resemblance to cannon.js. There are various facets to your query, but I'll strive to provide a comprehensive explanation.

The initial step involves setting the gravity. In the examples, this is achieved as follows:

var scene = new Physijs.Scene({ fixedTimeStep: 1 / 120 });
scene.setGravity(new THREE.Vector3( 0, -30, 0 ));

Next, you need to define the plane on which the dice rests as a rigid body, as well as the dice itself.

var dice = new Physijs.BoxMesh(
    new THREE.CubeGeometry(5, 5, 5), //the collision geometry
    new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture('images/dicetexture.jpg' )});, // material of the dice
    5, // mass, use 0 for the plane to indicate it doesn't move
    { restitution: .2, friction: .8 } //contact material
);

Lastly, you must apply a force. Although I couldn't locate an example immediately, a quick perusal of the source code revealed:

// Physijs.Mesh.applyForce
Physijs.Mesh.prototype.applyForce = function ( force, offset ) {
    if ( this.world ) {
        this.world.execute( 'applyForce', { id: this._physijs.id, force_x: force.x, force_y : force.y, force_z : force.z, x: offset.x, y: offset.y, z: offset.z } );
    }
};

Both force and offset should be vectors, with force denoting the direction and magnitude, and offset indicating the origin point.

I intend to conduct further experimentation with physi.js as it appears to have resolved certain issues I've been contemplating. If the problem persists, I'll provide an example.

Regarding allowing it to rotate a specific number of times at a predetermined height, that may necessitate extensive tinkering with the values...

EDIT 2:

In the fiddle you shared, the issue you described pertained to an undefined variable, effect.

if (intersects.length > 0) {
    intersects[ 0 ].applyImpulse(effect, offset);
}

Modify this to:

if (intersects.length > 0) {
    var effect = new THREE.Vector3( 0, 100, 0 );
    var offset = new THREE.Vector3( 0, 0, 0 );
    intersects[ 0 ].object.applyImpulse(effect, offset);
}

While the values are indeed defined, they are defined within a different function.

function apply_force(){
    var effect = new THREE.Vector3( 0, 100, 0 );
    var offset = new THREE.Vector3( 0, 0, 0 );
    object.applyImpulse( effect, offset );
}

Since this function is no longer utilized, you may consider removing it.

CLICK TIMER:

if(canClick == true){
    //process click
    canClick = false;
    setTimeout(function(){canClick = true}, 5000)//5 seconds before the user can click again.
}

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

Custom Typescript type that runs concurrently with the base type is disregarded

Assumption: When creating a custom type that mirrors an existing type, the expectation is for variables assigned to that type to maintain it and not default back to the base type. In the function f provided below, the expected return type should be Dog ins ...

Directive unable to recognize ng-pattern functionality

I am attempting to encapsulate an <input> within a directive in order to manage date validation, conversion from string to Date object, and keep the Date version in the original scope. The functionality seems to be working as intended. However, the n ...

Leveraging the power of AWS API Gateway and Lambda for seamless image upload and download operations with Amazon

I have successfully created a lambda function to handle image uploads and downloads to s3. However, I am encountering difficulties with the proxy integration from the API Gateway. Despite reviewing the documentation and looking at this specific question ...

Exploring the World of Angular JS Services

Following the recommended practices, I am working on encapsulating my global functions into reusable factory services. In the provided code snippet, my objective is to execute a function that takes the string value of "Qprogress" from my JSON data, perform ...

Proceed with downloading the file only when a checkbox has been ticked off and the form has been

Is there a way to make a PDF download only when a user checks a checkbox and submits the form, rather than just checking the checkbox and hitting submit? I am limited to using Jquery or plain javascript and do not have access to backend files. The checkbox ...

What is the best way to create subpages within a survey?

If I want to create a survey page on the web with multiple questions, but I am facing a challenge. I do not want to have several different pages and use a "Next Button" that links to another page. I am struggling to come up with ideas on how to implement ...

Storing binary data uploaded via AJAX in PHP on the server is essential for maintaining

I successfully imported a .png image file as an Array Buffer. var readSingleFile = function(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); ...

Leveraging the power of JavaScript Math methods to dictate the Co-ordinates of HTML Canvas .fillRect

Greetings to everyone! I have dedicated my entire evening to understanding how to implement the (Math.floor(Math.random()) function as the coordinates for the .fillRect method on an HTML canvas element. Despite searching through this website and various ...

Issue with Selenium webdriver's element.click() method not operating as anticipated in Chrome while using Mocha framework

While testing the log in feature of a website, I encountered an issue where the .click() method did not perform as expected despite being able to locate the Login button. Here is the relevant JavaScript test code: driver.sleep(1000) driver.findElement(By ...

using async.waterfall with async.apply

Here is a code snippet that I am working with: async.waterfall([ // Read directory async.apply(fs.readdir, '../testdata'), // Load data from each file function(files, callback) { async.each(files, loadDataFromFile, callback); } ], ...

Ensure that the context is used to effectively clear any existing data from the previous bar chart

I recently came across a cool codepen demo on this link. Upon clicking the first button followed by the second, the data transitions smoothly. However, there seems to be an issue where when hovering randomly over the bar charts at this source, the value ...

How can I pass a dynamic scope variable to a JavaScript function in AngularJS that is being updated within an ng-repeat loop?

In my HTML, I have an ng-repeat loop where a variable is displayed in table rows. I want the user to be able to click on a value and pass it to a JavaScript function for further action. The code snippet below showcases my earlier version which successful ...

Revealed the previously hidden private variables within the Revealing Module Pattern

I have encountered an issue while implementing the Revealing Module Pattern, as I am struggling to expose a modified private property. var myRevealingModule = (function(){ var name = 'Samantha'; function updateName () { name = ...

Is it possible for issues to arise when serving a web app using the "Globals" module in the Mean Stack?

Looking to transfer a variable (a constructed filename) from one file to another within an API can be quite challenging. One solution that comes to mind is utilizing globals, but with my current code structure, it seems like the only viable option. To addr ...

The addition of meshes in real-time leads to a decrease in control responsiveness

I'm currently working on creating a 3D map using Three.js. My process involves building the geometry and texture with images of size 256x256 pixels, then constructing a THREE.Mesh to add to the scene upon completion. However, I've noticed that ...

What is preventing me from accessing arguments.callee within this function in sloppy mode?

In attempting to retrieve the arguments.callee property in the following basic function, I encountered an error preventing me from doing so. function foo(a = 50, b) { console.log(arguments.callee); } foo(10, 50); Why is this issue occurring? It appe ...

Having trouble with the Slide Toggle menu closing unexpectedly?

$('span.nav-btn').click(function () { $('ul#menu').slideToggle(); }) $(window).resize(function () { if ( $(window).width() > 900) { $('ul#menu').removeAttr('style') } }); $('spa ...

Guide to locating the recursive function in Node.js runtime

As a beginner in the world of node and angular development, I have encountered a major issue - "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory". Is there anyone who can help me identify the function ...

Tips on incorporating the authorization header in the $.post() method with Javascript

When attempting to POST data to the server, I need to include an Authorization header. I attempted to achieve this using: $.ajax({ url : <ServiceURL>, data : JSON.stringify(JSonData), type : 'POST', contentType : "text/html", ...

Having trouble establishing a connection between Node.js and SQL Server using Tedious library

When attempting to connect to a local SQL Server instance using Node.js and Tedioius, I encounter the following error: { [ConnectionError: Failed to connect to XXXXX:1433 - connect ECONNREFUSED] name: 'ConnectionError', message: 'Failed ...