chandlerprall / Physijs

Physics plugin for Three.js
MIT License
2.77k stars 455 forks source link

How can I setGravity like earth at sphere? #292

Open kltk opened 7 years ago

kltk commented 7 years ago

Thank you!

frabert commented 7 years ago

I have not tried the library yet, but you may want to try to set a constant force directed towards the center of the sphere to all the affected objects... Also this way you could modulate the intensity based on the distance.

ghost commented 7 years ago

@ccrzz as stated in #134, this feature isn't integrated into Physijs right now. As suggested by @frabert, a possible workaround would involve taking the position vector of the sphere to apply gravity on, and subtract it by the position vector of the "earth" body. Then, normalize the difference to get the direction of gravity. The vector will be pointing outwards of the "earth", so just negate it. After that, multiply it by some gravity force, increasing exponentially as you approach "earth" or something. Finally, apply it to your sphere as your linear velocity by averaging that vector with the existing linear velocity value (not sure if this is totally realistic).

Just note that for proper space results you should obviously have global gravity for your scene set to [0, 0, 0].

I have here a snippet of the explanation:

// Assume `fbody` is the sphere, `earth` is the "earth" body.

var diff = fbody.position.clone().sub(earth.position);
var bvel = fbody.normalize().negate();

// Gravity force
var grav = 9.82;
bvel.multiplyScalar(grav);

// Average it out
bvel.add(fbody.getLinearVelocity()).multiplyScalar(0.5);
fbody.setLinearVelocity(bvel);