Skip to content

Instantly share code, notes, and snippets.

@sabha
Created September 22, 2017 20:40
Show Gist options
  • Save sabha/a70cc62e807823d62bfd49083f99a1df to your computer and use it in GitHub Desktop.
Save sabha/a70cc62e807823d62bfd49083f99a1df to your computer and use it in GitHub Desktop.
Circle - Velocity - Acceleration
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="400" height="600">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
function Vector(x,y) {
this.x = x;
this.y = y;
}
Vector.prototype.add = function(vec) {
this.x += vec.x;
this.y += vec.y;
};
Vector.prototype.sub = function(vec) {
this.x -= vec.x;
this.y -= vec.y;
};
Vector.prototype.mag = function() {
return Math.sqrt(((this.x*this.x)+(this.y*this.y)));
};
Vector.prototype.mul = function(val) {
this.x *= val;
this.y *= val;
};
Vector.prototype.nor = function() {
this.x /= this.mag();
this.y /= this.mag();
};
var canvas = document.getElementById('canvas'),
cw = canvas.width,
ch = canvas.height,
cx = null,
fps = 60,
position = new Vector(200,200),
velocity = new Vector(0,0),
mouseX = 0,
mouseY = 0,
acceleration = new Vector(0,0),
accelerate = false,
car = new Image();
function writeMousePos() {
var message = 'Mouse position: ' + mouseX + ',' + mouseY;
cx.font = '18pt Calibri';
cx.fillStyle = 'white';
cx.fillText(message, 10, 25);
}
canvas.addEventListener('mousemove', function(evt) {
var rect = canvas.getBoundingClientRect();
mouseX = evt.clientX - rect.left;
mouseY = evt.clientY - rect.top;
}, false);
canvas.addEventListener('mousedown', function() { accelerate = true; }, false);
canvas.addEventListener('mouseup', function() { accelerate = false; acceleration = new Vector(0,0); }, false);
function gameLoop() {
cx.clearRect(0,0,cw,ch);
cx.fillStyle = "rgb(24,24,24)";
cx.fillRect(0, 0, cw,ch);
writeMousePos();
cx.beginPath();
cx.fillStyle = 'red';
cx.arc(position.x, position.y, 20, 0, Math.PI * 360);
cx.fill();
var mouseVector = new Vector(mouseX, mouseY);
mouseVector.sub(position);
acceleration = new Vector(mouseVector.x, mouseVector.y);
acceleration.nor();
acceleration.mul(.05);
//cx.drawImage(car, position.x, position.y);
cx.arc(position.x, position.y, 20, 0, Math.PI * 360);
if(accelerate) {
if(velocity.mag() <= 10) {
velocity.add(acceleration);
}
position.add(velocity);
}
//if(position.y <= 0) { position.y = ch; }
}
if (typeof (canvas.getContext) !== undefined) {
cx = canvas.getContext('2d');
//cx.translate(200,200);
//drawing of the test image - img1
car.onload = function () {
cx.drawImage(car, 200, 200);
};
car.src = 'Car.png';
setInterval(gameLoop, 1000 / fps);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment