How to make "you died" symbol when you die - javascript

I tried making a game but I can't the "you died" symbol to work. I don't know how to use JavaScript to create my text inside the canvas.
Also, is there a way to create a myBlockPad variable that stops you from going through it but still lets you move elsewhere?
var myGamePiece;
var myObstacle;
var myBlockPad;
function startGame() {
myGamePiece = new component(40, 40, "#00ff00ff", 50, 140);
myObstacle = new component(10, 200, "#cf0000ff", 300, 120);
myBlockPad = new component(40, 80, "#7e3f00", 0, 120);
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 560;
this.canvas.height = 320;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e) {
myGameArea.key = false;
})
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
document.createElement("/* this is where the game over text goes*/").innerHTML;
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
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() {
if (myGamePiece.crashWith(myObstacle)) {
myGameArea.stop();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
}
if (myGameArea.key && myGameArea.key == 37 || myGameArea.key && myGameArea.key == 65) {
myGamePiece.speedX = -3;
} else if (myGameArea.key && myGameArea.key == 39 || myGameArea.key && myGameArea.key == 68) {
myGamePiece.speedX = 3;
} else if (myGameArea.key && myGameArea.key == 38 || myGameArea.key && myGameArea.key == 87) {
myGamePiece.speedY = -3;
} else if (myGameArea.key && myGameArea.key == 40 || myGameArea.key && myGameArea.key == 83) {
myGamePiece.speedY = 3;
} else {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
myGamePiece.update();
}
<!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()">
</body>
</html>

ctx.fillText(text,xAxis,yAxis);
E.g. ctx.fillText("You died",50,50);
Change colour is ctx.fillStyle="red";
Change font and size = ctx.font="30px Arial";

Related

problems with resizing sprites

I need to resize my spritesheet so it fits the correct dimensions of my game object. I have been looking around the internet and I found that this -ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);- is what i think i need to use. however, i do not know how or where to implement this in my code. i know how it works but i dont know where to put it or where in my code to put it. i use almost completely javascript
var myGamePiece;
var myObstacle;
var object1;
var objects;
var box;
function startGame() {
//creation of objects
wall = new component(30, 100, "black", 300, 200);
myGamePiece = new component(30, 30, "red", 240, 135);
myObstacle = new component(100, 100, "green", 200, 100);
object1 = new component(30, 30, "enemy.png", 340, 125, "image");
box = new component(30, 30, "box.png", 177, 145, "image");
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.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
collide : function() {
object1.x += 1;
object1.y += 1;
},
//what to do when pushing box
boxleft : function() {
box.x -= 1;
x -= 1;
}
}
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.sx = x;
this.sy = y;
this.swidth = width;
this.sheight = height;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
if (type == "image") {
ctx.drawImage(this.image,
this.x,
this.y,
this.width,
this.height
);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
//code for gray square
this.crashWith = function(object1) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = object1.x;
var otherright = object1.x + (object1.width);
var othertop = object1.y;
var otherbottom = object1.y + (object1.height);
var crash = true;
if ((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
return crash;
}
//code to push box
this.pushboxWith = function(box) {
const myleft = this.x;
const myright = this.x + (this.width);
const mytop = this.y;
const mybottom = this.y + (this.height);
const boxleft = box.x-2;
const boxright = box.x + (box.width)+2;
const boxtop = box.y+2;
const boxbottom = box.y + (box.height)-2;
var pushboxleft = true;
var pushboxright = true;
//test if pushing box
if ((myleft < boxright) && (mybottom >= boxtop) && (mytop <= boxbottom) && (myleft > boxleft)) {
pushboxleft = true;
} else {
pushboxleft = false;
}
return pushboxleft;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(object1)) {
myGameArea.collide();
} else if (myGamePiece.pushboxWith(box)) {
myGameArea.boxleft();
} else {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
//keyboard controls. moves everything but the player
if (myGameArea.key && myGameArea.key == 37) {
myObstacle.x += 2;
object1.x += 2;
box.x += 2;
wall.x += 2;
}
if (myGameArea.key && myGameArea.key == 39) {
myObstacle.x += -2;
object1.x += -2;
box.x += -2;
wall.x += -2;
}
if (myGameArea.key && myGameArea.key == 38) {
myObstacle.y += 2;
object1.y += 2;
box.y += 2;
wall.y += 2
}
if (myGameArea.key && myGameArea.key == 40) {
myObstacle.y += -2;
object1.y += -2;
box.y += -2;
wall.y += -2
}
//other square movement. disabled to isolate code.
/*
if (object1.x < myGamePiece.x) {
object1.x += 1;
}
if (object1.x > myGamePiece.x) {
object1.x += -1;
}
if (object1.y < myGamePiece.y) {
object1.y += 1;
}
if (object1.y > myGamePiece.y) {
object1.y += -1;
}
*/
/* object order: the object that is higher on the list
will be on top of objects lower on the list
*/
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
wall.update();
object1.update();
box.update();
//end of list
}
}
i do use some 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()">
<script src="main.js"></script>
</body>
</html>
if you need to test my code you can find it here- https://eeeegame-2.octopuscat.repl.co/

i cant get my shot to travel directly to my cursor

I am making a 2d game with javascript and i can't get the shot to travel in a line directly to the cursor. I want it so when the shoot function is called th make the shot travel to the cursor and not alter the path when the cursor is moved after the shot is already out. Right now it is onnly going diagonal to the player
<!DOCTYPE html>
<html lang="en" onclick="shoot()">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8">
<style>
canvas {
border:4px solid #000000;
background-color: #26af2d;
}
</style>
<body onload="startGame()">
<div name="buttonDiv">
<button type="button" id="startRoundBtn" onclick= startWave();>dont mind this</button>
</div>
<p id="demo">
</p>
<script>
let playerHealth = 100;
let shot = false;
let enemyOut = false;
let waveActive = false;
let enemyDmg = 25;
let playerImmuneTime = 0;
//start
var player;
var TopEdge;
var BottomEdge;
var RightEdge;
var LeftEdge;
let Enemy;
var projectile;
function startGame() {
player = new component(30, 30, "red", 10, 120);
TopEdge = new component(10000, 200, "purple", 0, -200);
BottomEdge = new component(10000, 1, "purple", 0, 500);
RightEdge = new component(1000, 500, "purple", 1150, 0);
LeftEdge = new component(1000, 500, "purple", -1000, 0);
var x = document.getElementById("startRoundBtn");
myGameArea.start();
}
//game area
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1150;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,
document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 10);
window.addEventListener('keydown', function (e) {
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function(){
clearInterval(this.interval);
}
}
//coords
var pointerX = 0;
var pointerY = 0;
document.onmousemove = function(event) {
pointerX = event.pageX;
pointerY = event.pageY;
}
setInterval(pointerCheck, 1);
function pointerCheck() {
var cursorCoords = 'Cursor Location: '+pointerX+'X, '+pointerY+'Y health: ' + playerHealth + ' imune time:' +playerImmuneTime
document.getElementById("demo").innerHTML = cursorCoords;
}
//compenents
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
//new pos
this.newPos = function() {
this.X += this.speedX;
this.Y += this.speedY;
}
//crashing
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;
}
}
//updates
function updateGameArea() {
myGameArea.clear();
if (playerHealth > 0) {
player.newPos();
player.update();
}
TopEdge.update();
BottomEdge.update();
RightEdge.update();
LeftEdge.update();
if (shot == true) {
projectile.update();
projectile.newPos();
projectile.speedX = 0;
projectile.speedY = 0;
}
if (enemyOut == true && playerHealth > 0) {
if (Enemy.crashWith(player) && playerImmuneTime <= 0) {
playerHealth = playerHealth -= enemyDmg;
playerImmuneTime = 50;
} if (playerImmuneTime >= 0) {
playerImmuneTime -= 1;
}
Enemy.newPos();
Enemy.update();
Enemy.speedX = 0;
Enemy.speedY = 0;
}
player.speedX = 0;
player.speedY = 0;
//movement
if (myGameArea.keys[65] ) {player.speedX = -2.5; }
if (myGameArea.keys[68] ) {player.speedX = 2.5; }
if (myGameArea.keys[87] ) {player.speedY = -2.5; }
if (myGameArea.keys[83] ) {player.speedY = 2.5; }
if (myGameArea.keys[82]) {waveActive = true;}
if (myGameArea.keys[75]) {waveActive = false;}
if (enemyOut == true && player.x >= Enemy.x) {Enemy.speedX = 1; }
if (enemyOut == true && player.x <= Enemy.x) {Enemy.speedX = -1; }
if (enemyOut == true && player.y >= Enemy.y) {Enemy.speedY = 1; }
if (enemyOut == true && player.y <= Enemy.y) {Enemy.speedY = -1; }
if (waveActive == true && enemyOut == false) {
createEnemy();
}
if (shot == true && pointerX > player.x) {projectile.speedX = 10};
if (shot == true && pointerX < player.x) {projectile.speedX = -10};
if (shot == true && pointerY > player.y) {projectile.speedY = 10};
if (shot == true && pointerY < player.y) {projectile.speedY = -10};
if (shot == true && enemyOut == true && projectile.crashWith(Enemy)) {
shot = false;
enemyOut = false;
waveActive = false;
}
//edges of game area
if (player.crashWith(TopEdge) && myGameArea.keys[87]) {
player.speedY = 0;
}
if (player.crashWith(RightEdge) && myGameArea.keys[68]) {
player.speedX = 0;
}
if (player.crashWith(BottomEdge) && myGameArea.keys[83]) {
player.speedY = 0;
}
if (player.crashWith(LeftEdge) && myGameArea.keys[65]) {
player.speedX = 0;
}
player.x += player.speedX;
player.y += player.speedY;
Enemy.x += Enemy.speedX;
Enemy.y += Enemy.speedY;
projectile.x += projectile.speedX;
projectile.y += projectile.speedY;
}
function createEnemy() {
Enemy = new component(30, 30, "purple",
Math.floor(Math.random() * 1100),
Math.floor(Math.random() * 500));
enemyOut = true;
}
function shoot() {
let midPlayerX = player.x + 12;
let midPlayerY = player.y + 12;
projectile = new component(5, 5, "white", midPlayerX, midPlayerY);
shot = true;
}
</script>
</body>
</html>
you need to 'freeze' the pointerX and pointerY values between the shot being fired and reaching its destination (otherwise those values will change on mousemove).
You already have shot=true when the projectile is launched so it can be read in a conditional you add to your mousemove event listener. That will take care of freezing the pointers when the projectile is fired :
document.onmousemove = function (event) {
if (!shot) {
pointerX = event.pageX
pointerY = event.pageY
} // prevent updates to pointers when shot is fired;
}
but you will need to reactivate the listener by setting shot to false when the projectile colides with the stored pointerX and pointerY values.

How to create a collision in a Snake Game?

I am currently creating a Snake Game in html and java script and i am having difficulties creating a collision where the snake (known as 'myGamePiece' in code)(green block)is not colliding with the obstacle (known as 'myObstacle' in code)(red block) and adding 5 extra blocks to the snake. How could i resolve this issue?
I have tried implementing and editing other pieces of code into my game and have been using the W3 schools game tutorial as part of a guide for my game but it doesn't provide or give a clear solution as what i could for my solution.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #000000;
background-color: #000000;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(20, 20, "green", 10, 120);
myObstacle = new component(20, 20, "red", 300, 120);
myGameArea.start();
}
//Creates the Game Canvas:
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 900;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
//create the movement with the KeyBoard Arrows:
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myObstacle.update();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -1; }
if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 1; }
if (myGameArea.key && myGameArea.key == 38) {myGamePiece.speedY = -1; }
if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }
myGamePiece.newPos();
myGamePiece.update();
}
</script>
</body>
</html>
I expect the output to be that when the Game piece collides with the obstacle, 5 more green blocks are added to the end of the game piece, but nothing happens when it collides together.
I created simple function checkCollision() I suggest you to improve it and calculate if there is collision of object given in parameters and then return true, and handle collision in another function.
In that way you will be able to use the same function to check collision with other objects and don't need to rewrite it.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #000000;
background-color: #000000;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(20, 20, "green", 10, 120);
myObstacle = new component(20, 20, "red", 300, 120);
myGameArea.start();
}
//Creates the Game Canvas:
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 900;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
//create the movement with the KeyBoard Arrows:
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myObstacle.update();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -1; }
if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 1; }
if (myGameArea.key && myGameArea.key == 38) {myGamePiece.speedY = -1; }
if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }
myGamePiece.newPos();
myGamePiece.update();
checkCollision(); //check collision
}
function checkCollision()
{
if(Math.abs(myGamePiece.x - myObstacle.x) < myGamePiece.width) //if difference of X of 2 objects is less than with of object, you can replace it with your desired value
if(Math.abs(myGamePiece.y - myObstacle.y) < myGamePiece.height) //the same for the height
console.log("collision"); // handle collision here
}
startGame();
</script>
</body>
</html>
if you got questions don't hesitate to ask

Javascript game, collision detection when hitting a wall

I've been following W3schools tutorial on creating a JavaScript game in a canvas https://www.w3schools.com/graphics/game_obstacles.asp
I've got to the stage where they add an obstacle in. Currently, it has collision detection which stops the game when it hits the wall. I am trying to figure out a way to treat it like a wall where the box could hit it and no longer move that direction and continue the game, making the wall work.
Heres what I've got so far:
https://jsfiddle.net/j9cy1mne/1/
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle;
var speed = 3;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myObstacle = new component(10, 200, "green", 300, 120);
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.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
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() {
if (myGamePiece.crashWith(myObstacle)) {
console.log("crash");
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
}
}
document.onkeydown = checkKeyD;
function checkKeyD(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
myGamePiece.speedY = -speed;
} else if (e.keyCode == '40') {
// down arrow
myGamePiece.speedY = speed;
} else if (e.keyCode == '37') {
// left arrow
myGamePiece.speedX = -speed;
} else if (e.keyCode == '39') {
// right arrow
myGamePiece.speedX = speed;
}
}
document.onkeyup = clearmove;
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
</script>
</body>
I see that you have part of it finished. You just need to have the crash code in the if statement for moving the player right. This will run the code only when the player is pressing the right arrow.
else if (e.keyCode == '39') {
// right arrow
// add crash code here
myGamePiece.speedX = speed;
}
Your game loop only executes when there is no crash:
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
console.log("crash");
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
}
}
What you want to do is to set the myGamePiece.speedX and myGamePiece.speedX to 0 when a collision is detected. Something like:
function updateGameArea() {
myGameArea.clear();
myObstacle.update();
if (myGamePiece.crashWith(myObstacle)) {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
}
Edit: You probably want to apply some code to "back up" when a collision is detected, so the pieces are no longer in a collided state

Create event for an image that's on canvas

I am trying to make this: When I click on an image that is on the canvas, a message pops out or another image shows up (some event). I don't understand why my code doesn't work. Can someone help me? Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border: 5px solid #d3d3d3;
background-color: #F08080;
}
</style>
</head>
<body onload="startGame()">
<script>
var backgroundMusic;
function startGame() {
myGameArea.start();
myPlayer = new component(300,300,"dort.png", 10, 120, "image");
backgroundMusic = new sound("panjabi.mp3")
backgroundMusic.play();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1200;
this.canvas.height = 700;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e){
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.left = x
this.update = function() {
ctx = myGameArea.context;
if (type == "image") {
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height); } }
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myPlayer.speedX = 0;
myPlayer.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {myPlayer.speedX = -10}
if (myGameArea.key && myGameArea.key == 39) {myPlayer.speedX = 10}
if (myGameArea.key && myGameArea.key == 38) {myPlayer.speedY = -10}
if (myGameArea.key && myGameArea.key == 40) {myPlayer.speedY = 10}
myPlayer.newPos();
myPlayer.update();
}
function sound(src) {
this.sound = document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.style.display = "none";
document.body.appendChild(this.sound);
this.play = function() {
this.sound.play();
}
this.stop = function(){
this.sound.pause();
}
}
$('#canvas').click(function (e) {
var clickedX = e.pageX - this.offsetLeft;
var clickedY = e.pageY - this.offsetTop;
for(var i = 0; i < myPlayer[i].length; i++) {
if(clickedX < myPlayer[i].right && clickedX > myPlayer[i].left &&
clickedY > myPlayer[i].top && clickedY < myPlayer[i].bottom) {
alert('clicked number');
}
}
});
</script>
</body>
</html>
My first guess: $('#canvas') finds the element with the id "canvas", but your canvas element does not have any id set.
Does it work if you do something like this.canvas.id = 'canvas' in the start function?

Categories

Resources