I'm new to Javascript and canvas. I'm working on a simple canvas race game that randomly sets the speed two rectangles (Red & Blue). I have it set so they both stop at a certain point. When one car wins, it prints out "Red/Blue Won!" on the canvas.
I have the racing part down, but I'm stuck on figuring out how to run the conditional statement, where to put it, and have it print out when 1 rectangle has reached the end of the race/ certain point first.
if (square1 gets passed finish line first or stops moving) {
// Draw to canvas
context.font = "20pt sans-serif";
context.fillText("Red is The Winner!", 5, 25, 300);
context.fillStyle = "red";
}
else if (square2 gets passed finish line first or stops moving) {
context.font = "20pt sans-serif";
context.fillText("Blue is The Winner!", 5, 280, 300);
context.fillStyle = "blue";
}
I'm not sure if its the way I have it animated using time. Any help would be much appreciated.
Here is the animation code
var animateRed = function(prop, val, duration) {
// The calculations required for the step function
var start = new Date().getTime();
var end = start + duration;
var current = square1[prop];
var distance = val - current;
var step = function() {
// Get our current progres
var timestamp = new Date().getTime();
var progress = Math.min((duration - (end - timestamp)) / duration, 1);
// Update the square's property
square1[prop] = current + (distance * progress);
// If the animation hasn't finished, repeat the step.
if (progress < 1) requestAnimationFrame(step);
};
// Start the animation
return step();
};
var animateBlue = function(prop, val, duration) {
// The calculations required for the step function
var start = new Date().getTime();
var end = start + duration;
var current = square2[prop];
var distance = val - current;
var step = function() {
// Get our current progres
var timestamp = new Date().getTime();
var progress = Math.min((duration - (end - timestamp)) / duration, 1);
// Update the square's property
square2[prop] = current + (distance * progress);
// If the animation hasn't finished, repeat the step.
if (progress < 1) requestAnimationFrame(step);
};
// Start the animation
return step();
};
$("#go").on('click', function() {
//Math.floor(Math.random() * 1000) + 100;
var speedRed = Math.floor(Math.random() * 1000) + 500;
var speedBlue = Math.floor(Math.random() * 1000) + 500;
animateRed('x', 450, speedRed);
animateBlue('x', 450, speedBlue);
});
************** Updated Fiddle ******************** accidentally posted wrong one
Here is my fiddle of it: Fiddle