JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<button onclick="Start()">Start</button>
<button onclick="Brake()">Brake</button>
<button onclick="Reset()">Reset</button>
</div>
<img id="car" src="https://dl.dropboxusercontent.com/u/37981960/Images/so/smallcar.png" />
JavaScript
var animate = -1;
var INTERVAL = 1 / 30; // 30 FPS
var imgObj = document.getElementById('car');
imgObj.style.position = 'relative';
imgObj.style.left = '200px';
imgObj.style.top = '350px';
// create a simulation model
var car = {
texture: imgObj,
stopped: true,
position: {
x: 200,
y: 350
},
velocity: {
x: 0,
y: 0
},
maxSpeed: 15,
acceleration: 0,
setPosition: function (x, y) {
this.position.x = x;
this.position.y = y;
this.acceleration = 0;
this.fixedVelocity(0, 0);
this.stopped = true;
},
accelerate: function (accel) {
this.acceleration = accel;
this.stopped = false;
},
isBreaking: false,
brake: function (force) {
this.isBreaking = true;
this.acceleration = -force;
},
fixedVelocity: function (vx, vy) {
this.acceleration = 0;
this.velocity.x += vx;
this.velocity.y += vy;
},
update: function (dt) {
if (!this.stopped) {
this.velocity.y += this.acceleration * dt;
this.position.y -= this.velocity.y * dt;
this.velocity.y = (this.velocity.y > this.maxSpeed ? this.maxSpeed : this.velocity.y);
if (this.velocity.y <= 0) {
this.velocity.y = 0;
this.stopped = true;
this.acceleration = 0;
}
}
},
draw: function () {
this.texture.style.left = this.position.x + 'px';
this.texture.style.top = this.position.y + 'px';
}
}
function Start() {
// set the car acceleration
car.accelerate(5);
if (animate == -1) {
animate = setInterval(function () {
car.update(INTERVAL);
car.draw();
}, INTERVAL);
}
}
function Brake() {
if (animate != -1) {
car.brake(2);
}
}
function Reset() {
...