How to make my object fire bullets one by one? - javascript

The main object keeps firing bullets and it looks like a lazer. I don't know how to make it fire one bullet at a press of a key. Do I need to use intervals?
var gameBullet=[];
var i=0;
//Starts game
function startGame() {
myGameArea.start();
myGamePiece= new component(20,20,"red",10,120);
}
//Creates canvas , events and how many times per sec should the object redraw
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, 1);
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");
})
window.addEventListener('space',function(e){
myGameArea.keys[e.keyCode] = (e.type == "space");
})
},
clear: function(){
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
}
}
//Bullet constructor
function bullet(width,height,color,x,y){
this.gamearea=myGameArea;
this.width=width;
this.height=height;
this.speedX=5;
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.hitBorder();
}
this.hitBorder = function() {
var right = myGameArea.canvas.width - this.width;
if (this.x > right) {
this.x = right;
}
}
}
//Main Object constructor
function component(width,height,color,x,y){
this.gamearea=myGameArea;
var imageObj = new Image();
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.drawImage(imageObj,this.x,this.y, this.width, this.height);
imageObj.src = 'stalin.png';
*/
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos= function(){
this.x+=this.speedX;
this.y+=this.speedY;
this.hitBorder();
}
this.hitBorder = function() {
var down = myGameArea.canvas.height - this.height;
if (this.y > down) {
this.y = down;
}
if (this.y < 0) {
this.y = 0;
}
var right = myGameArea.canvas.width - this.width;
if (this.x > right) {
this.x = right;
}
if (this.x < 0) {
this.x = 0;
}
}
}
I think here is the problem. I need to add something in the loop, but I don't know what.
//Updates game
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -1; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 1; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -1; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 1; }
if (myGameArea.keys && myGameArea.keys[32])
{
gameBullet[i]=new bullet(5,5,"red",myGamePiece.x,myGamePiece.y);
i=i+1;
}
myGamePiece.newPos();
myGamePiece.update();
for( i=0;i<gameBullet.length;i+=1){
gameBullet[i].newPos();
gameBullet[i].update();
}
}
startGame();

you can use setinterval() in place of for loop
setinterval(yourcode,timespan);

Related

How do i shoot bullets 360* using keyboard while rotating a object in canvas?

I want my object to shoot in the direction my object is facing when it rotates or moves, any ideas on how to do it?
I'm a beginner as well i started few days ago so its pretty hard on me to find the codes and to learn them as well as i cant find a good teacher or a website for it.
this is the code, I tried something but I'm pretty sure it was a total failure..
var myGamePiece;
function startGame() {
bullet = new component(5, 5, 'blue', 300, 300);
myGamePiece = new component(30, 30, "red", 225, 225);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1400;
this.canvas.height = 750;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
e.preventDefault();
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
stop : function() {
clearInterval(this.interval);
},
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.width = width;
this.height = height;
this.speedx = 0;
this.speedy = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.s = x;
this.u = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speedx;
this.y += this.speedy;
this.s += this.speed * Math.sin(this.angle);
this.u -= this.speed * Math.cos(this.angle);
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.moveAngle = 0;
myGamePiece.speedx = 0;
myGamePiece.speedy = 0;
bullet.speed = 0;
if (myGameArea.keys && myGameArea.keys[90]) {myGamePiece.moveAngle = -3; }
if (myGameArea.keys && myGameArea.keys[88]) {myGamePiece.moveAngle = 3; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedy= -2; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedy= 2; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedx= 2; }
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedx= -2; }
if (myGameArea.keys && myGameArea.keys[32]) {bullet.speed= -3; }
bullet.newPos();
bullet.update();
myGamePiece.newPos();
myGamePiece.update();
}
window.onload = function() {
var myGamePiece;
var bullet;
var myGameArea;
var ctx;
function startGame() {
bullet = new component(5, 5, 'blue', 300, 300);
myGamePiece = new component(30, 30, "red", 225, 225);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1400;
this.canvas.height = 750;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
bullet.speed = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
e.preventDefault();
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
stop : function() {
clearInterval(this.interval);
},
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.width = width;
this.height = height;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.speed = 0;
this.speedx = 0;
this.speedy = 0;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speedx;
this.y += this.speedy;
this.x += this.speed * Math.cos(this.angle);
this.y += this.speed * Math.sin(this.angle);
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.moveAngle = 0;
myGamePiece.speedx = 0;
myGamePiece.speedy = 0;
if (myGameArea.keys && myGameArea.keys[90]) {myGamePiece.moveAngle = -3; }
if (myGameArea.keys && myGameArea.keys[88]) {myGamePiece.moveAngle = 3; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedy= -2; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedy= 2; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedx= 2; }
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedx= -2; }
if (myGameArea.keys && myGameArea.keys[32]) {
bullet.angle = myGamePiece.angle;
bullet.x = myGamePiece.x;
bullet.y = myGamePiece.y;
bullet.speed= 3;
}
bullet.newPos();
bullet.update();
myGamePiece.newPos();
myGamePiece.update();
}
startGame();
}
You almost had it working, the biggest issue was bullet.speed = 0; in game loop was making it never move.
You were also updating this.s and this.u but it was never used elsewhere so I fixed this part.
this.s += this.speed * Math.sin(this.angle);
this.u -= this.speed * Math.cos(this.angle);
I've also added some extra code so it fires from the red cube position.
Best comparing yours code against my changes to see what else changed but I think I've highlighted the major point.

How to implement onkeyup function with a specific key

I am trying to create a basic platformer game, and I'm working on the gravity section. I am using some if myGameArea.keys statements to allow the player to move their character forwards and backwards, and up. I am using an accelerate function to stop gravity when the up key is pressed, but I can't make it start again when the key is lifted. I know how to implement the onkeyup function (onkeyup = function();) but I don't know how to add it to my code.
<!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()">
<script>
var myGamePiece;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 10, 240);
}
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.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keyup");
})
},
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.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.05;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
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;
}
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
myGamePiece.gravity = 0.1;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -2;
}
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 2;
}
if (myGameArea.keys && myGameArea.keys[38]) {accelerate(-0.2)}
myGamePiece.newPos();
myGamePiece.update();
}
function accelerate(n) {
myGamePiece.gravity = n;
}
</script>
</body>
</html>
This is only a small portion of the code. If anyone would like the full amount, comment below to tell me, please. Thanks for your help!
Some issues:
In your keyup event handler, you have:
myGameArea.keys[e.keyCode] = (e.type == "keyup");
But this will set the property value to true. You want false, so just do:
myGameArea.keys[e.keyCode] = false;
(BTW, this error was not there in one of your previous question versions, where you had (e.type == "keydown").
You can also simply set to true in the keydown handler (but there was no error there).
Secondly, the gravitySpeed keeps increasing even when you hit the bottom. This will make that value incredible great, and the counter accelaration when pressing the up key will not have any visible effect, unless you wait long enough. Instead, reset `gravitySpeed here::
this.y = rockbottom;
this.gravitySpeed = 0; // <----
See it run:
var myGamePiece;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 10, 240);
}
var myGameArea = {
canvas: document.createElement("canvas"),
keys: [], // <--- just initialise here
start: function() {
window.focus();
this.canvas.width = 480;
this.canvas.height = 180;
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.keys[e.keyCode] = true; // <---
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = 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;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.05;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
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; // <----
}
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
myGamePiece.gravity = 0.1;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -2; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 2; }
if (myGameArea.keys && myGameArea.keys[38]) {accelerate(-0.2)}
myGamePiece.newPos();
myGamePiece.update();
}
function accelerate(n) {
myGamePiece.gravity = n;
}
window.onload = startGame;
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}

stop a character jumping in mid-air in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am creating a platformer in javascript, and I am making a gravity sytem on it. What happens is that gravity is reduced when the player presses the up arrow key. The problem is that the user can press the up arrow multiple times and jump whilst already jumping. Any way to sort this out?
Here is my code:
<!DOCTYPE>
<html>
<head>
<style>
canvas {
border: 1px solid #000000;
background-color: rgb(0, 200, 200);
}
</style>
</head>
<body onload = "startGame()">
<canvas id="myCanvas" width="750" height="300">
<script>
var myGamePiece;
var floor;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 10, 230);
floor = new component(750, 10, "green", 0, 260);
}
var myGameArea = {
canvas : document.getElementById('myCanvas'),
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.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);
}
}
function component(width, height, color, x, y) {
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.05;
this.gravitySpeed = 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.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 - 10;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
}
function updateGameArea() {
myGameArea.clear();
floor.update();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.keys && myGameArea.keys[37]) {
myGamePiece.speedX = -2.5;
}
if (myGameArea.keys && myGameArea.keys[39]) {
myGamePiece.speedX = 2.5;
}
if (myGameArea.keys && myGameArea.keys[38]) {
accelerate(-0.2)
} else{
accelerate(0.1)
}
if (myGameArea.keys && myGameArea.keys[40]) {
myGamePiece.speedY = 2.5;
}
myGamePiece.newPos();
myGamePiece.update();
}
function accelerate(n) {
myGamePiece.gravity = n;
}
</script>
</canvas>
</body>
</html>
You only need to check myGamePiece.y >=230 before accelarting
I have changed only two things in your code and it works fine
if (myGameArea.keys && myGameArea.keys[40] && myGamePiece.y >= 230) last if block of your function updateGameArea()
Second Last if block of your updateGameArea()
if (myGameArea.keys && myGameArea.keys[38]) {
if(myGamePiece.y >= 230) accelerate(-0.2)
}
var myGamePiece;
var floor;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 10, 230);
floor = new component(750, 10, "green", 0, 260);
}
var myGameArea = {
canvas : document.getElementById('myCanvas'),
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.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);
}
}
function component(width, height, color, x, y) {
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.05;
this.gravitySpeed = 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.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 - 10;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
}
function updateGameArea() {
myGameArea.clear();
floor.update();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.keys && myGameArea.keys[37]) {
myGamePiece.speedX = -2.5;
}
if (myGameArea.keys && myGameArea.keys[39]) {
myGamePiece.speedX = 2.5;
}
if (myGameArea.keys && myGameArea.keys[38]) {
if(myGamePiece.y >= 230) accelerate(-0.2)
} else{
accelerate(0.1)
}
if (myGameArea.keys && myGameArea.keys[40] && myGamePiece.y >= 230) {
myGamePiece.speedY = 2.5;
}
myGamePiece.newPos();
myGamePiece.update();
}
function accelerate(n) {
myGamePiece.gravity = n;
}
<body onload = "startGame()">
<canvas id="myCanvas" width="750" height="300">
Hope it helps

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