HTML5 Canvas Collision Detection - html

So I have been looking around and trying tutorials but I can't seem to get any collision detection systems to work. If someone would be able to explain what I am doing wrong or any syntax errors that would be great.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bouncing Ball</title>
<style>
#mycanvas {
outline: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="1280" height="750"></canvas>
<script>
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
var xx = 50;
var yy = 100;
var velY = 0;
var velX = 0;
var speed = 6;
var friction = 0.7;
var keys = [];
var velocity = 0;
var acceleration = 1;
function physics() {
velocity+=acceleration;
yy += velocity;
if(yy > 597) {
var temp =0;
temp =velocity/4;
velocity=-temp;
yy = 597;
}
}
function collision(first, second){
return !(first.x > second.x + second.width || first.x + first.width < second.x || first.y > second.y + second.height || first.y + first.height < second.y);
}
var player = {
color: "#2B2117",
x: xx,
y: yy,
width: 75,
height: 75,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(xx, yy, this.width, this.height);
}
}
var floor = {
color: "#A67437",
x: 0,
y: 670,
width: 1280,
height: 80,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
var bucket = {
color: "#B25E08",
x: 300,
y: 600,
width: 50,
height: 100,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function update() {
if (keys[39]) {
if (velX < speed) {
velX+=3;
}
}
if (keys[37]) {
if (velX > -speed) {
velX--;
}
}
if (keys[32]) {
velY -= 1.5;
velY += 1;
}
velX *= friction;
xx += velX;
yy += velY;
physics();
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.rect(0,0,canvas.width, canvas.height);
ctx.fillStyle = "#EEE3B9";
ctx.fill();
floor.draw();
bucket.draw();
player.draw();
if (collision(player, bucket)) {
console.log('collision');
}
setTimeout(update, 10);
}
update();
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
</script>
</body>

I can only append to what markE already says in his answer (we seem to be working on this simultaneously :) ).
I will first point out a more serious bug in the code:
You are using fill() without a beginPath() first. This will slow down the code loop rapidly. Replace fill() with a fillRect() instead.
Also, there is no need to use clearRect() when the next draw operation fills the entire canvas:
//ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#EEE3B9";
ctx.fillRect(0, 0, canvas.width, canvas.height);
You're using global vars xx/yy. One main point of using objects is to avoid global vars. The render method uses the same so it appears to work, but the player's local properties are never updated. Remove global vars and only work with the object's x and y (I would recommend some refactoring so you can pass in the object to the physics() etc. instead of doing global referencing).
var xx = 50;var yy = 100;
To:
var player = {
x: 50, // numbers cannot be referenced, their value
y: 100, // is copied. Use these properties directly instead..
// ...
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height); // and here..
}
}
and
function physics() {
//...
player.y += velocity;
if (player.y > 597) {
//...
player.y = 597;
}
}
and in the loop:
player.x += velX;
player.y += velY;
Add preventDefault() in you key handlers to prevent the key moves to affect the brower's window scroll (not all users have a large screen so the left/right key will also affect the scrolling).
document.body.addEventListener("keydown", function(e) {
e.preventDefault();
...
And of course, use requestAnimationFrame to loop the animation.
I would also recommend using a function object that can be instantiated as you have methods in all of them. With a function object you can prototype the draw() method and share it across all the instances without the need of extra memory (and it's good for the internal optimizer as well). This if you plan to draw more than those three objects.
Updated code
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
var velY = 0;
var velX = 0;
var speed = 6;
var friction = 0.7;
var keys = [];
var velocity = 0;
var acceleration = 1;
function physics() {
velocity += acceleration;
player.y += velocity;
if (player.y > 597) {
var temp = 0;
temp = velocity / 4;
velocity = -temp;
player.y = 597;
}
}
function collision(first, second) {
return !(first.x > second.x + second.width || first.x + first.width < second.x || first.y > second.y + second.height || first.y + first.height < second.y);
}
var player = {
color: "#2B2117",
x: 50,
y: 100,
width: 75,
height: 75,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
var floor = {
color: "#A67437",
x: 0,
y: 670,
width: 1280,
height: 80,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
var bucket = {
color: "#B25E08",
x: 300,
y: 600,
width: 50,
height: 100,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function update() {
if (keys[39]) {
if (velX < speed) {
velX += 3;
}
}
else if (keys[37]) {
if (velX > -speed) {
velX -= 3;
}
}
else if (keys[32]) {
velY -= 1.5;
velY += 1;
}
velX *= friction;
player.x += velX;
player.y += velY;
physics();
//ctx.clearRect(0, 0, canvas.width, canvas.height); // not really needed
ctx.fillStyle = "#EEE3B9";
ctx.fillRect(0, 0, canvas.width, canvas.height); // as this clears too...
floor.draw();
bucket.draw();
player.draw();
if (collision(player, bucket)) {
console.log('collision');
}
requestAnimationFrame(update);
}
update();
document.body.addEventListener("keydown", function(e) {
e.preventDefault();
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
e.preventDefault();
keys[e.keyCode] = false;
});
#mycanvas {outline: 1px solid #000;}
<canvas id="mycanvas" width="1280" height="750"></canvas>

There's no problem with your collision function--it will correctly recognize the collision between any 2 un-rotated rectangles.
Visually, your black rect drops to the floor, bounces once or twice and then settles on the floor.
3 issues though...
I do see that your setTimeout is set to trigger every 10ms. That's a bit fast since the display will only refresh about every 1000/60=16.67ms--so your setTimeout should be at least 16.67. Also, You might consider using requestAnimationFrame instead of setTimeout because rAF synchronizes itself with the display and gives better performance.
One design glitch, even if the user constantly holds down the right-key to move the rect towards the bucket as fast as possible, the rect is never given enough "delta X" to hit the bucket.
You are testing collisions with player and bucket but you are not updating the player.x & player.y. Therefore your collision() is only testing the initial player position and not its current position.
// in update()
...
player.x=xx;
player.y=yy;
Demo of refactored code:
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
var xx = 50;
var yy = 100;
var velY = 0;
var velX = 0;
var speed = 6;
var friction = 0.7;
var keys = [];
var velocity = 0;
var acceleration = 1;
function physics() {
velocity+=acceleration;
yy += velocity;
if(yy > 597) {
var temp =0;
temp =velocity/4;
velocity=-temp;
yy = 597;
}
}
function collision(first, second){
return !(first.x > second.x + second.width || first.x + first.width < second.x || first.y > second.y + second.height || first.y + first.height < second.y);
}
var player = {
color: "#2B2117",
x: xx,
y: yy,
width: 75,
height: 75,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(xx, yy, this.width, this.height);
}
}
var floor = {
color: "#A67437",
x: 0,
y: 670,
width: 1280,
height: 80,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
var bucket = {
color: "#B25E08",
x: 50,
y: 600,
width: 50,
height: 100,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function update() {
if (keys[39]) {
if (velX < speed) {
velX+=3;
}
}
if (keys[37]) {
if (velX > -speed) {
velX--;
}
}
if (keys[32]) {
velY -= 1.5;
velY += 1;
}
velX *= friction;
xx += velX;
yy += velY;
//
player.x=xx;
player.y=yy;
physics();
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.rect(0,0,canvas.width, canvas.height);
ctx.fillStyle = "#EEE3B9";
ctx.fill();
floor.draw();
bucket.draw();
player.draw();
if (collision(player, bucket)) {
alert('collision when player at:'+player.x+"/"+player.y);
}else{
setTimeout(update, 1000/60*3);
}
}
update();
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
<canvas id="mycanvas" width="1280" height="750"></canvas>

Copy and paste
<html>
<head>
<title> new </title>
<script>
var ctx1;
var ctx;
var balls = [
{x:50, y:50, r:20, m:1, vx:1, vy:1.5},
{x:200, y:80, r:30, m:1, vx:-1, vy:0.3},
];
function start()
{
ctx1 = document.getElementById("ctx");
ctx = ctx1.getContext("2d");
ctx.strokeStyle = "blue";
ctx.lineWidth = 2;
setInterval(draw, 10);
}
function draw()
{
ctx.clearRect(0, 0, ctx1.width, ctx1.height);
for (var a = 0; a < balls.length; a ++)
{
for (var b = 0; b < balls.length; b ++)
{
if (a != b)
{
var distToBalls = Math.sqrt(Math.pow(balls[a].x - balls[b].x, 2) + Math.pow(balls[a].y - balls[b].y, 2));
if (distToBalls <= balls[a].r + balls[b].r)
{
var newVel = getBallCollision(balls[a], balls[b]);
balls[a].vx = newVel.ball1.vx;
balls[a].vy = newVel.ball1.vy;
balls[b].vx = newVel.ball2.vx;
balls[b].vy = newVel.ball2.vy;
balls[a].x += balls[a].vx;
balls[a].y += balls[a].vy;
balls[b].x += balls[b].vx;
balls[b].y += balls[b].vy;
}
}
}
}
for (var a = 0; a < balls.length; a ++)
{
ctx.beginPath();
ctx.arc(balls[a].x, balls[a].y, balls[a].r, 0, Math.PI*2, true);
ctx.fill();
ctx.closePath();
if (balls[a].x <= balls[a].r) balls[a].vx *= -1;
if (balls[a].y <= balls[a].r) balls[a].vy *= -1;
if (balls[a].x >= ctx1.width - balls[a].r) balls[a].vx *= -1;
if (balls[a].y >= ctx1.height - balls[a].r) balls[a].vy *= -1;
balls[a].x += balls[a].vx;
balls[a].y += balls[a].vy;
}
}
function getBallCollision(b1, b2)
{
var dx = b1.x - b2.x;
var dy = b1.y - b2.y;
var dist = Math.sqrt(dx*dx + dy*dy);
if (Math.abs(dy) + Math.abs(dx) != 0 && dist <= b1.r + b2.r)
{
var colAng = Math.atan2(dy, dx);
var sp1 = Math.sqrt(b1.vx*b1.vx + b1.vy*b1.vy);
var sp2 = Math.sqrt(b2.vx*b2.vx + b2.vy*b2.vy);
var dir1 = Math.atan2(b1.vy, b1.vx);
var dir2 = Math.atan2(b2.vy, b2.vx);
var vx1 = sp1 * Math.cos(dir1 - colAng);
var vy1 = sp1 * Math.sin(dir1 - colAng);
var vx2 = sp2 * Math.cos(dir2 - colAng);
var vy2 = sp2 * Math.sin(dir2 - colAng);
var fvx1 = ((b1.m - b2.m) * vx1 + (2 * b2.m) * vx2) / (b1.m + b2.m);
var fvx2 = ((2 * b1.m) * vx1 + (b2.m - b1.m) * vx2) / (b1.m + b2.m);
var fvy1 = vy1;
var fvy2 = vy2;
b1.vx = Math.cos(colAng) * fvx1 + Math.cos(colAng + Math.PI/2) * fvy1;
b1.vy = Math.sin(colAng) * fvx1 + Math.sin(colAng + Math.PI/2) * fvy1;
b2.vx = Math.cos(colAng) * fvx2 + Math.cos(colAng + Math.PI/2) * fvy2;
b2.vy = Math.sin(colAng) * fvx2 + Math.sin(colAng + Math.PI/2) * fvy2;
return { ball1:b1, ball2:b2 };
}
else return false;
}
</script>
</head>
<body onLoad="start();">
<canvas id="ctx" width="500" height="300" style = "border : 2px solid #854125 ;"> </canvas>
</body>
</html>

Related

How do I add gravity in a simple game?

So I've been making a simple game and I want gravity, but I don't know where to start. I
would like it if I could change the speed that the pieces fall, but whatever works best is fine. Could someone please help me because I have no idea.
Here's my code so far...
Also, this is modified to fit the small preview, so full screening won't work very well.
canvas {
border: 1px solid #000;
}
<HTML>
<canvas id="canvas" style="position: absolute; left: 0px; top: 0px;"></canvas>
<script>
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.width = innerWidth-4;
canvas.height = innerHeight-10;
canvas.style.backgroundColor = '#87CEEB';
var x = 150,
y = 180,
velY = 0,
velX = 0,
speed = 2,
friction = 0.95,
keys = [];
function update() {
requestAnimationFrame(update);
if (keys[87]) {
if (velY > -speed) {
velY--;
}
}
if (keys[68]) {
if (velX < speed) {
velX++;
}
}
if (keys[65]) {
if (velX > -speed) {
velX--;
}
}
if (keys[38]) {
if (velY > -speed) {
velY--;
}
}
if (keys[39]) {
if (velX < speed) {
velX++;
}
}
if (keys[37]) {
if (velX > -speed) {
velX--;
}
}
velY *= friction;
y += velY;
velX *= friction;
x += velX;
if (x >= 1345) {
x = 1345;
} else if (x <= 5) {
x = 5;
}
if (y > 180) {
y = 180;
} else if (y <= 5) {
y = 5;
}
ctx.clearRect(0, 0, 2000, 1000);
ctx.beginPath(),
player = new component(x, y, 'black', 10, 10);
ctx.fill();
}
function component(x, y, color, width, height) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
update();
document.body.addEventListener('keydown', function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener('keyup', function(e) {
keys[e.keyCode] = false;
});
</script>
</html>

simulate onmouseup event to canvas

i have a simple HTML5 with a canvas object, i just need to add replicate the same events on the button below the code-
As you can see pushing the button, the canvas calls accelerate() and onmouseUp event calls the function again with different argument, and the canvas stops going up and starts with the gravity
I would like to use in a touch screen, the only problem is the event OnmuseUp that i do not know how to manage
this is the code:
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.canvas.addEventListener('click', function() {accelerate(-0.2);}, false);
updateGameArea();
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
if (this.type == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
function accelerate(n) {
if (!myGameArea.interval) {myGameArea.interval = setInterval(updateGameArea, 20);}
myGamePiece.gravity = n;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Click the ACCELERATE button to start the game</p>
<p>How long can you stay alive? Use the ACCELERATE button to stay in the air..</p>
</body>
</html>
Rather than use the event listener to drive the game, use the event listener just to track the input state.
Eg
canvas.addEventListener("mousedown",inputEvent);
canvas.addEventListener("touchstart",inputEvent);
const input = {
active : false;
}
function inputEvent(){
input.active = true;
}
Then rather than use setInterval (which you should never use for animation) create a main loop function
function mainLoop(){
// see answer below
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
This will start being called every 1/60th second. In this you monitor the input and do what is needed depending on the game state.
const thrust = -0.4;
const gravity = 0.1;
var inplay = false; // when true game is playing.
function mainLoop(){
if(input.active && !inplay){
inplay = true;
input.active = false; // clear the input
}
if(inplay){
if(input.active){ // input
myGamePiece.speedY += thrust;
input.active = false; // clear input
}
updateGameArea(); // call the render game function.
}
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
You will need to change the move function
You had
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
Change to
this.newPos = function() {
this.speedY += gravity;
this.x += this.speedX;
this.y += this.speedY;
this.hitBottom();
}
Or you can change the input to have a thrust over some frames
const input = {
active : 0;
}
const thrustFrameCount = 4;
function inputEvent(){
input.active = thrustFrameCount;
}
and change the main loop to
const thrust = -0.1;
const gravity = 0.1;
var inplay = false; // when true game is playing.
function mainLoop(){
if(input.active > 0 && !inplay){
inplay = true;
input.active = 0; // clear the input
}
if(inplay){
if(input.active > 0){ // input
myGamePiece.speedY += thrust * input.active;
input.active -= 1; // count down input on.
}
updateGameArea(); // call the render game function.
}
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
Well everything is sort of like that, your game code is a little bit overly complex so I have hacked a quick mod to give you an example of what I meant in the above answer.
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : canvas,
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
this.frameNo = 0;
updateGameArea();
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
if (this.type == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.speedY += gravity;
this.x += this.speedX;
this.y += this.speedY;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
if(this.speedY > 0){
this.speedY = 0;
}
}
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
return;
}
}
myGameArea.clear();
if (myGameArea.frameNo % wallFrameCount === 0 ) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
myGameArea.frameNo += 1;
}
canvas.addEventListener("mousedown",inputEvent);
canvas.addEventListener("touchstart",inputEvent);
const input = {active : 0 };
const thrustFrameCount = 4;
function inputEvent(){
input.active = thrustFrameCount;
}
const wallFrameCount = 200;
const thrust = -0.4;
const gravity = 0.2;
var inplay = false; // when true game is playing.
function mainLoop(){
if(input.active > 0 && !inplay){
startGame();
inplay = true;
input.active = 0; // clear the input
}
if(inplay){
if(input.active > 0){ // input
myGamePiece.speedY += thrust * input.active;
input.active -= 1; // count down input on.
}
updateGameArea(); // call the render game function.
}
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
<canvas id="canvas" width="480" height="270"></canvas><br>
Click touch canvas to start.

Combine multiple HTML5 canvas animations

I have this jsfiddle
http://jsfiddle.net/t9L6g3bd/4/
// requestAnimationFrame Shim
(function () {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var endPercent = 101;
var curPerc = 0;
var counterClockwise = false;
var circ = Math.PI * 2;
var quart = Math.PI / 2;
context.lineWidth = 2;
context.strokeStyle = '#333';
animate();
function animate(current) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(x, y, radius, -(quart), ((circ) * current) - quart, false);
context.stroke();
curPerc++;
if (curPerc < endPercent) {
requestAnimationFrame(function () {
animate(curPerc / 100)
});
} else {
ex(126, 126);
cross(126, 126);
//fadein(0);
}
}
function fadein(a) {
context.lineWidth = 1.5;
context.globalAlpha = a;
context.beginPath();
context.moveTo(166, 84);
context.lineTo(84, 166);
context.stroke();
context.beginPath();
context.moveTo(166, 166);
context.lineTo(84, 84);
context.stroke();
if (a != 0.8) {
requestAnimationFrame(function () {
fadein(a + 0.01);
});
}
}
function ex(x, y) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(84, x);
context.lineTo(168, y);
context.stroke();
if (x != 168) {
requestAnimationFrame(function () {
ex(x + 1, y - 1)
});
}
}
function cross(x, y) {
// context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(84, x);
context.lineTo(168, y);
context.stroke();
if (x != 84) {
requestAnimationFrame(function () {
cross(x - 1, y + 1)
});
}
}
I was wondering if there was a way to combine the circle animation and the x at the same time, or one after the other so that they both are on the screen and both have smooth edges
You needed to refactor your code.
Link to refactored jsfiddle
function animate() {
if (curPerc < endPercent) {
context.clearRect(0, 0, canvas.width, canvas.height);
drawCircle(curPerc / 100);
fadeIn(curPerc / 100);
curPerc++;
requestAnimationFrame(function () {
animate();
});
}
}
Basically you needed to change your code so that only one animation loop is running, and on each loop iteration call an update function for each animation. I would say though, that the code overall is kind of difficult to maintain and you should consider further refactoring to rectify this. Hope this helps.
You should indeed use only one requestAnimationFrame, because its overhead is quite big, but mainly for the clarity of your code (hard to know as it is which object is animating or not).
-->> What about storing all the animation data into objects, and even letting the object animate / draw themselves ?
This way you have a clear separation of concerns, and changing one aspect of the animation is much easier.
I started to do this in this fiddle :
http://jsfiddle.net/0200h552/6/
the animation loop becomes quite simple :
function animate() {
requestAnimationFrame(animate);
context.clearRect(0, 0, canvas.width, canvas.height);
//
circle.draw();
if (!circle.animate()) {
ex.draw();
cross.draw();
ex.animate();
cross.animate();
}
}
And here are the three objects in use :
var circle = {
x: centerX,
y: centerY,
radius: 75,
curPerc: 0,
endPercent: 101,
animate: function () {
if (this.curPerc < this.endPercent) {
this.curPerc++;
return true;
}
return false;
},
draw: function () {
var perc = this.curPerc / this.endPercent;
var oldAlpha = context.globalAlpha;
context.globalAlpha = perc;
context.beginPath();
context.arc(this.x, this.y, this.radius, -(quart), ((circ) * perc) - quart, false);
context.stroke();
context.globalAlpha = oldAlpha;
}
};
The "ex" :
var ex = {
x: centerX,
y: centerY,
animate: function () {
if (this.x != 168) {
this.x++;
this.y--;
return true;
}
return false;
},
draw: function () {
var x = this.x;
var y = this.y;
context.beginPath();
context.moveTo(84, x);
context.lineTo(168, y);
context.stroke();
}
};
The cross :
var cross = {
x: centerX,
y: centerY,
animate: function () {
if (this.x != 84) {
this.x--;
this.y++;
return true;
}
return false;
},
draw: function () {
var x = this.x;
var y = this.y;
context.beginPath();
context.moveTo(84, x);
context.lineTo(168, y);
context.stroke();
}
};

Canvas Game Timer

I'm making a HTML5 Canvas Game with a rectangle that moves around the canvas. The objective is to dodge multiple Balls moving across the canvas for as long as possible. But i'm struggling to put a Timer to show your Time/Score when a ball hits the rectangle. (The rectangle is moved by the UP,DOWN,LEFT and RIGHT keys). Anyone with knowledge of this that could help me out would be much appreciated, thanks.
Here’s how to integrate a timer into your game:
Set the startingTime just before you start the game ticker:
/* Do the function, call every 20 milliseconds*/
startTime=new Date();
Draw the elapsed time whenever playGame is called:
/* MAIN GAME */
function playGame()
{
g.clearRect(0, 0, canvas.width, canvas.height); //Clear canvas at start.
player.draw();
for (var i = 0; i < 8; i++)
{
ball[i].move();
ball[i].draw();
}
// draw the score
drawElapsedTime();
}
And finally, draw the final score when the game is over:
drawFinalScore();
alert("GAME OVER");
Also, I noticed you left the game ticker running even after the game ended. Here’s how to turn off the ticker:
// turn on the ticker and get a reference to the object
var theInterval=setInterval(playGame, 20);
// turn off the ticker
clearInterval(theInterval);
And…check out the new requestAnimationFrame ticker. It’s much more efficient and resource friendly than the older setInterval ticker. Here’s a link for requestAnimationFrame: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/8qKht/
<!DOCTYPE html>
<html>
<head>
<style>
body
{
background-color:green;
}
#simpleCanvas
{
position: absolute;
top: 20%;
left: 30%;
border:2px solid blue;
width:500px;
height:500px;
background-color: yellow;
}
</style>
<script>
/* Ball Array */
var ball = new Array();
ball[0] = new Ball(150, 150); // x location of target, y location of target
ball[1] = new Ball(200, 350);
ball[2] = new Ball(400, 350);
ball[3] = new Ball(320, 250);
ball[4] = new Ball(440, 190);
ball[5] = new Ball(100, 350);
ball[6] = new Ball(80, 120);
ball[7] = new Ball(130, 240);
/* Player */
var player = new Player();
var score;
/* PLAYER OBJECT */
function Player()
{
/* private member variables */
var x = 10;
var y = 10;
var playerColour = "red";
var width = 25;
var height = 30;
var speed = 10;
/* public methods */
this.draw = draw;
function draw()
{
g.fillStyle = playerColour;
g.fillRect(x, y, width, height);
this.isHit();
}
this.setX = setX;
function setX(newX)
{
x = newX;
}
this.getX = getX;
function getX()
{
return x;
}
this.setY = setY;
function setY(newY)
{
y = newY;
}
this.getY = getY;
function getY()
{
return y;
}
this.getSpeed = getSpeed;
function getSpeed()
{
return speed;
}
this.getW = getW;
function getW()
{
return width;
}
this.getH = getH;
function getH()
{
return height;
}
this.isHit = isHit;
function isHit()
{
for (var i = 0; i < ball.length; i++)
{
if (((x + width) >= ball[i].getX()) && ((x + width) <= (ball[i].getX() + (ball[i].getRadius() * 2)))
&& ((y + height) >= ball[i].getY()) && ((y + height) <= (ball[i].getY() + (ball[i].getRadius() * 2))))
{
clearInterval(theInterval);
drawFinalScore();
//alert("GAME OVER");
console.log("game over");
}
}
}
}
/* BALL OBJECT */
function Ball(newX, newY)
{
var x = newX;
var y = newY;
var dx = 2;
var dy = 4;
var radius = 10;
var targetColour = "blue";
/* public methods */
this.draw = draw;
function draw()
{
g.beginPath();
g.fillStyle = targetColour;
g.arc(x, y, radius, 0, Math.PI * 2);
g.fill();
g.closePath();
}
this.setX = setX;
function setX(newX)
{
x = newX;
}
this.getX = getX;
function getX()
{
return x;
}
this.setY = setY;
function setY(newY)
{
y = newY;
}
this.getY = getY;
function getY()
{
return y;
}
this.getRadius = getRadius;
function getRadius()
{
return radius;
}
this.move = move;
function move()
{
x += dx;
y += dy;
// Bounce on a left or right edge.
if (x + dx > canvas.width - radius || x + dx < radius)
{
dx = -dx;
}
// If ball hits the top, bounce it.
else if (y + dy < radius)
{
dy = -dy;
}
//If the ball hits the bottom, check see if it hits a paddle.
else if (y + dy > canvas.height - radius)
{
dy = -dy;
}
}
}
/* MAIN GAME */
function playGame()
{
g.clearRect(0, 0, canvas.width, canvas.height); //Clear canvas at start.
player.draw();
for (var i = 0; i < 8; i++)
{
ball[i].move();
ball[i].draw();
}
// draw the score
drawElapsedTime();
}
/* SCORE */
var startTime;
// ending elapsed time in seconds
var score;
function drawElapsedTime(){
var elapsed=parseInt((new Date() - startTime)/1000);
g.save();
g.beginPath();
g.fillStyle="red";
g.font="14px Verdana"
// draw the running time at half opacity
g.globalAlpha=0.50;
g.fillText(elapsed+" secs",canvas.width-75,25);
g.restore();
}
function drawFinalScore(){
// set the final score just once
if(score==null){ score=parseInt((new Date() - startTime)/1000); }
g.save();
g.beginPath();
g.fillStyle="red";
g.font="30px Verdana"
g.fillText("Game Over: "+score+" secs",50,35);
g.restore();
}
function arrowKeyDown(e)
{
var stepSize = 10; //Increase size
if (e.keyCode == 37) // left
{
player.setX(player.getX() - player.getSpeed());
if (player.getX() < 0)
{
player.setX(0);
}
}
else if(e.keyCode == 38) // up
{
player.setY(player.getY() - player.getSpeed());
if (player.getY() < 0)
{
player.setY(0);
}
}
else if(e.keyCode == 39) // right
{
player.setX(player.getX() + player.getSpeed());
if ((player.getX() + player.getW()) > canvas.width)
{
player.setX(canvas.width - player.getW());
}
}
else if(e.keyCode == 40) // down
{
player.setY(player.getY() + player.getSpeed());
if ((player.getY() + player.getH()) > canvas.height)
{
player.setY(canvas.height - player.getH());
}
}
}
document.addEventListener('keydown',arrowKeyDown);
</script>
</head>
<body>
<h1>A V O I D</h1>
<canvas id="simpleCanvas"></canvas>
<script>
/* Get the canvas id */
var canvas = document.getElementById("simpleCanvas");
/* Give the canvas a width and height */
/* The width and height are in canvas logical units */
canvas.width = 500;
canvas.height = 500;
/* Assign a graphics context to the canvas, so that we can draw on it */
var g = canvas.getContext("2d");
/* Do the function, call every 20 milliseconds*/
startTime=new Date();
var theInterval=setInterval(playGame, 20);
</script>
<audio src="intense.mp3" autoplay loop></audio>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<h1>
A V O I D
</h1>
<style>
body
{
background-color:green;
}
#simpleCanvas
{
position: absolute;
top: 20%;
left: 30%;
border:2px solid blue;
width:500px;
height:500px;
background-color: yellow;
}
}
</style>
<script>
/* Ball Array */
enter code here`var ball = new Array();
ball[0] = new Ball(150, 150); // x location of target, y location of target
ball[1] = new Ball(200, 350);
ball[2] = new Ball(400, 350);
ball[3] = new Ball(320, 250);
ball[4] = new Ball(440, 190);
ball[5] = new Ball(100, 350);
ball[6] = new Ball(80, 120);
ball[7] = new Ball(130, 240);
/* Player */
var player = new Player();
var score;
/* PLAYER OBJECT */
function Player()
{
/* private member variables */
var x = 10;
var y = 10;
var playerColour = "red";
var width = 25;
var height = 30;
var speed = 10;
/* public methods */
this.draw = draw;
function draw()
{
g.fillStyle = playerColour;
g.fillRect(x, y, width, height);
this.isHit();
}
this.setX = setX;
function setX(newX)
{
x = newX;
}
this.getX = getX;
function getX()
{
return x;
}
this.setY = setY;
function setY(newY)
{
y = newY;
}
this.getY = getY;
function getY()
{
return y;
}
this.getSpeed = getSpeed;
function getSpeed()
{
return speed;
}
this.getW = getW;
function getW()
{
return width;
}
this.getH = getH;
function getH()
{
return height;
}
this.isHit = isHit;
function isHit()
{
for (var i = 0; i < ball.length; i++)
{
if (((x + width) >= ball[i].getX()) && ((x + width) <= (ball[i].getX() + (ball[i].getRadius() * 2)))
&& ((y + height) >= ball[i].getY()) && ((y + height) <= (ball[i].getY() + (ball[i].getRadius() * 2))))
{
alert("GAME OVER");
}
}
}
}
/* BALL OBJECT */
function Ball(newX, newY)
{
var x = newX;
var y = newY;
var dx = 2;
var dy = 4;
var radius = 10;
var targetColour = "blue";
/* public methods */
this.draw = draw;
function draw()
{
g.beginPath();
g.fillStyle = targetColour;
g.arc(x, y, radius, 0, Math.PI * 2);
g.fill();
g.closePath();
}
this.setX = setX;
function setX(newX)
{
x = newX;
}
this.getX = getX;
function getX()
{
return x;
}
this.setY = setY;
function setY(newY)
{
y = newY;
}
this.getY = getY;
function getY()
{
return y;
}
this.getRadius = getRadius;
function getRadius()
{
return radius;
}
this.move = move;
function move()
{
x += dx;
y += dy;
// Bounce on a left or right edge.
if (x + dx > canvas.width - radius || x + dx < radius)
{
dx = -dx;
}
// If ball hits the top, bounce it.
else if (y + dy < radius)
{
dy = -dy;
}
//If the ball hits the bottom, check see if it hits a paddle.
else if (y + dy > canvas.height - radius)
{
dy = -dy;
}
}
}
/* MAIN GAME */
function playGame()
{
g.clearRect(0, 0, canvas.width, canvas.height); //Clear canvas at start.
player.draw();
for (var i = 0; i < 8; i++)
{
ball[i].move();
ball[i].draw();
}
}
/* SCORE */
var isGameOver=false;
var startTime;
// ending elapsed time in seconds
var score;
function drawElapsedTime(){
var elapsed=parseInt((new Date() - startTime)/1000);
ctx.save();
ctx.beginPath();
ctx.fillStyle="red";
ctx.font="14px Verdana"
// draw the running time at half opacity
ctx.globalAlpha=0.50;
ctx.fillText(elapsed+" secs",canvas.width-75,25);
ctx.restore();
}
function drawFinalScore(){
// set the final score just once
if(score==null){ score=parseInt((new Date() - startTime)/1000); }
ctx.save();
ctx.beginPath();
ctx.fillStyle="red";
ctx.font="18px Verdana"
ctx.fillText("Game Over: "+score+" secs",20,25);
ctx.restore();
}
function arrowKeyDown(e)
{
var stepSize = 10; //Increase size
if (e.keyCode == 37) // left
{
player.setX(player.getX() - player.getSpeed());
if (player.getX() < 0)
{
player.setX(0);
}
}
else if(e.keyCode == 38) // up
{
player.setY(player.getY() - player.getSpeed());
if (player.getY() < 0)
{
player.setY(0);
}
}
else if(e.keyCode == 39) // right
{
player.setX(player.getX() + player.getSpeed());
if ((player.getX() + player.getW()) > canvas.width)
{
player.setX(canvas.width - player.getW());
}
}
else if(e.keyCode == 40) // down
{
player.setY(player.getY() + player.getSpeed());
if ((player.getY() + player.getH()) > canvas.height)
{
player.setY(canvas.height - player.getH());
}
}
}
document.addEventListener('keydown',arrowKeyDown);
</script>
</head>
<body>
<canvas id="simpleCanvas">
Your browser does not support the HTML5 <canvas> tag.
</canvas>
<script>
/* Get the canvas id */
var canvas = document.getElementById("simpleCanvas");
/* Give the canvas a width and height */
/* The width and height are in canvas logical units */
canvas.width = 500;
canvas.height = 500;
/* Assign a graphics context to the canvas, so that we can draw on it */
var g = canvas.getContext("2d");
/* Do the function, call every 20 milliseconds*/
setInterval(playGame, 20);
</script>
<audio src="intense.mp3" autoplay loop></audio>
</body>
</html>
/*This is my code and i tryed adding it in and making it function but it would not work ? Dont know what im doing wrong ? Thanks for the reply

Moving already Drawn shape on html5 canvas

I'm having trouble keeping one object on my canvas. The initially drawn box rendered it in the correct position, but it disappears when I drag it:
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
eraseAllButton = document.getElementById('eraseAllButton'),
strokeStyleSelect = document.getElementById('strokeStyleSelect'),
guidewireCheckbox = document.getElementById('guidewireCheckbox'),
drawingSurfaceImageData,
mousedown = {},
rubberbandRect = {},
dragging = false,
guidewires = guidewireCheckbox.checked,
w = 90, h = 90;
count = 0;
boxesXCo = 0;
boxesYCo = 0;
i = 0;
// Functions..........................................................
function drawGrid(color, stepx, stepy) {
context.save()
context.strokeStyle = color;
context.lineWidth = 0.5;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
for (var i = stepx + 0.5; i < context.canvas.width; i += stepx) {
context.beginPath();
context.moveTo(i, 0);
context.lineTo(i, context.canvas.height);
context.stroke();
}
for (var i = stepy + 0.5; i < context.canvas.height; i += stepy) {
context.beginPath();
context.moveTo(0, i);
context.lineTo(context.canvas.width, i);
context.stroke();
}
context.restore();
}
function windowToCanvas(x, y) {
var bbox = canvas.getBoundingClientRect();
return { x: x - bbox.left * (canvas.width / bbox.width),
y: y - bbox.top * (canvas.height / bbox.height) };
}
// Save and restore drawing surface...................................
function saveDrawingSurface() {
drawingSurfaceImageData = context.getImageData(0, 0,
canvas.width,
canvas.height);
}
function restoreDrawingSurface() {
context.putImageData(drawingSurfaceImageData, 0, 0);
}
function drawRubberbandShape(loc) {
context.beginPath();
context.moveTo(mousedown.x, mousedown.y);
//context.lineTo(loc.x, loc.y);
context.stroke();
}
function updateRubberband(loc) {
//updateRubberbandRectangle(loc);
context.restore();
drawRubberbandShape(loc);
}
// Guidewires.........................................................
function drawHorizontalLine (y) {
context.beginPath();
context.moveTo(0,y+0.5);
context.lineTo(context.canvas.width,y+0.5);
context.stroke();
}
function drawVerticalLine (x) {
context.beginPath();
context.moveTo(x+0.5,0);
context.lineTo(x+0.5,context.canvas.height);
context.stroke();
}
function drawGuidewires(x, y) {
context.save();
context.strokeStyle = 'rgba(0,0,230,0.4)';
context.lineWidth = 0.5;
drawVerticalLine(x);
drawHorizontalLine(y);
context.restore();
}
// Canvas event handlers..............................................
canvas.onmousedown = function (e) {
var loc = windowToCanvas(e.clientX, e.clientY);
e.preventDefault(); // prevent cursor change
context.restore();
saveDrawingSurface();
mousedown.x = loc.x;
mousedown.y = loc.y;
dragging = true;
if (i ==0)
i++;
else if(((mousedown.x<=(boxesXCo+w)&&(mousedown.x>=boxesXCo))&&
((mousedown.y<=(boxesYCo+h)&&(mousedown.y>=boxesYCo)))))
i--;
};
canvas.onmousemove = function (e) {
var loc;
if (dragging) {
e.preventDefault(); // prevent selections
loc = windowToCanvas(e.clientX, e.clientY);
restoreDrawingSurface();
//updateRubberband(loc);
if(guidewires) {
drawGuidewires(loc.x, loc.y);
}
}
if(((mousedown.x<=(boxesXCo+w)&&(mousedown.x>=boxesXCo))&&
((mousedown.y<=(boxesYCo+h)&&(mousedown.y>=boxesYCo))))
&& (dragging)&&(i == 1 )){
context.restore();
restoreDrawingSurface();
context.fillStyle = strokeStyleSelect.value;
context.fillRect(e.clientX,e.clientY,w,h);
};
//Trying to implement moving shapes but need to store values of drawn objs
};
canvas.onmouseup = function (e) {
loc = windowToCanvas(e.clientX, e.clientY);
restoreDrawingSurface();
updateRubberband(loc);
dragging = false;
if(i == 0);
else {
saveDrawingSurface();
restoreDrawingSurface();
context.fillRect(e.clientX,e.clientY, w, h);
boxesXCo = e.clientX;
boxesYCo = e.clientY;
context.restore();
i++;}
/*else if(i == 1)
{
context.restore();
}*/
//context.fillRect(mousedown.x,mousedown.y,w,h,"FF0982");
};
// Controls event handlers.......................................
eraseAllButton.onclick = function (e) {
context.clearRect(0, 0, canvas.width, canvas.height);
drawGrid('lightgray', 10, 10);
saveDrawingSurface();
count =0;
context.restore();
};
strokeStyleSelect.onchange = function (e) {
context.strokeStyle = strokeStyleSelect.value;
context.fillStyle = strokeStyleSelect.value;
};
guidewireCheckbox.onchange = function (e) {
guidewires = guidewireCheckbox.checked;
};
// Initialization................................................
context.strokeStyle = strokeStyleSelect.value;
context.fillStyle = strokeStyleSelect.value;
drawGrid('lightgray', 10, 10);
//context.fillRect(mousedown.x,mousedown.y,(mousedown.x+50),(mousedown.x+50),"FF0982");
//context.drawRect(mousedown.x-50,mousedown.y-50,mousedown.x+50,mousedown.y+50);
thanx again
Rather than drawing to canvas on each mouse movement, use window.requestFrameAnimation to draw constantly.
At a guess, I'd assume either the browser rendering is interfering or the coordinates are out but I can't run your code to make sure.
I've written some pseudo code that shows what I do for rendering things. You'll need to implement this for yourself, it won't run out of the box, it's just intended as a guide.
var Box = function() {
};
Box.prototype = {
x: 0,
y: 0,
draw: function (canvas) {
// draw the item on the canvas
}
};
var box = new Box();
window.requestAnimationFrame(function() {
box.draw(canvas);
window.requestAnimationFrame();
});
canvas.onmousemove = function(e) {
if (dragging) {
box.x = e.clientX;
box.y = e.clientY;
}
}