JSFiddle - React, Tailwind, and code Playground
HTML
<canvas width=400 height=350></canvas>
JavaScript
function Vector3(x, y, z) {
this.x=x;this.y=y;this.z=z
}
Vector3.prototype.Dot = function(a) {
return this.x*a.x+this.y*a.y+this.z*a.z;
}
Vector3.prototype.Normalize = function() {
var g = Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);
return new Vector3(this.x/g, this.y/g, this.z/g);
}
Vector3.prototype.add = function(n) {
return new Vector3(this.x+n, this.y+n, this.z+n);
}
Vector3.prototype.subtr = function(n) {
return new Vector3(this.x-n.x, this.y-n.y, this.z-n.z);
}
Vector3.prototype.addM = function(a) {
return new Vector3(this.x+a.x,this.y+a.y,this.z+a.z);
}
Vector3.prototype.mu = function(n) {
return new Vector3(this.x*n, this.y*n, this.z*n);
}
Vector3.prototype.div = function(n) {
return new Vector3(this.x/n, this.y/n, this.z/n);
}
Vector3.prototype.t = function() {
return this.x+", "+this.y+", "+this.z;
}
var momentum=null, velocity=null, position=null;
var gravity=null, force=null;
var mass=null;
gravity = new Vector3(0, -9.81, 0);// set to taste
mass = 100;//set to taste
position = new Vector3(50, 300, 0);//some arbitrary position.
momentum = new Vector3(Math.random(), 0, 0);//starts the momentum off in some random horizontal direction
momentum = momentum.Normalize();
momentum = momentum.mu(50);//set to taste just to give the system som speed at startup.
var ctx,
log = console.log.bind(console);
$(function() {
ctx = $('canvas')[0].getContext('2d');
});
var i = 0;
window.setInterval(function() {
var elapsed = 1000/200; // otherwise the ball stands still too fast...
force = new Vector3(0, 5, 0);
//set force for this frame to whatever, maybe input, maybe give system some lateral force?
momentum=momentum.addM(gravity.addM(force).mu(elapsed));
velocity = momentum.div(mass);
position = position.addM(velocity.mu(elapsed));
if (position.y < 0 && momentum.y < 0) {//if position is at floor & momentum heading downward
position.y = 0;//reset the object to floor level
var...