My game components won't draw onto the canvas after adding if/else statement.
The statement only checks if the game piece hit the game obstacle.
I tried changing attributes and rewrite some functions but it seems the problem hasn't been fixed.
Whenever I remove the if/else function, the components draw.
Here is part of the code that holds that if/else function:
if(gamePieceBorder.crashGame(gameObstacle) || gamePieceRed.crashGame(gameObstacle))
{
gameArea.stop();
}
else
{
obstacle.update();
gamePieceBorder.pos();
gamePieceBorder.move();
gamePieceBorder.update();
gamePieceRed.pos();
gamePieceRed.move();
gamePieceRed.update();
gameArea.clear();
}
For me not pasting an entire code, here is the pastebin link to the code: https://pastebin.com/HuiR7r7D
How can I get the components to draw? If someone fixes the code, what was the issue? I am not an expert at javascript but only a beginner.
There are several problems:
window.EventListener should be window.addEventListener
keyup and keydown should have no upper case letters
gameObstacle in that if is undefined (should be obstacle probably)
clear method should be called before drawing, not after it
Here is the corrected script: https://pastebin.com/bXpQ2qvB
//-----------------------------------------Variables
var gamePieceRed;
var gamePieceBorder;
var gameObstacle;
//-----------------------------------------
//-----------------------------------------Main game function
function startGame()
{
gamePieceRed = new component(22, 22, "rgb(255, 132, 156)", 10, 120);
gamePieceBorder = new component(24, 24, "black", 9, 119);
obstacle = new component(10, 200, "rgb(64, 0 ,12)", 300, 120)
gameArea.start();
}
//-----------------------------------------
//-----------------------------------------Creating game area and applying controls
var gameArea =
{
canvas : document.createElement("canvas"), start : function()
{
this.canvas.width = 510;
this.canvas.height = 280;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(gameUpdate, 20);
window.addEventListener("keydown", function (e)
{
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = true;
}, true)
window.addEventListener("keyup", function (e)
{
gameArea.keys[e.keyCode] = false;
}, true)
},
clear : function()
{
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function()
{
clearInterval(this.interval);
},
keyboard: function() {
if (this.keys) {
if (this.keys[37]) {gamePieceBorder.speedX = gamePieceRed.speedX = -2;}
else if (this.keys[39]) {gamePieceBorder.speedX = gamePieceRed.speedX = 2;}
else {gamePieceBorder.speedX = gamePieceRed.speedX = 0;}
if (this.keys[38]) {gamePieceBorder.speedY = gamePieceRed.speedY = -2;}
else if (this.keys[40]) {gamePieceBorder.speedY = gamePieceRed.speedY = 2;}
else {gamePieceBorder.speedY = gamePieceRed.speedY = 0;}
}
}
}
//-----------------------------------------
//-----------------------------------------Game component
function component(width, height, color, x, y)
{
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.update = function()
{
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height)
}
this.move = function()
{
this.x += this.speedX;
this.y += this.speedY;
}
this.crashGame = function(obj)
{
var left = this.x;
var right = this.x + (this.width);
var top = this.y;
var bottom = this.y + (this.height);
var otherLeft = obj.x;
var otherRight = obj.x + (obj.width);
var otherTop = obj.y;
var otherBottom = obj.y + (obj.height);
var crash = true;
if (bottom < otherTop || top > otherBottom || right < otherLeft || left > otherRight)
{
crash = false;
}
return crash;
}
}
//-----------------------------------------
//-----------------------------------------Game area updater
function gameUpdate()
{
if(gamePieceBorder.crashGame(obstacle) || gamePieceRed.crashGame(obstacle))
{
gameArea.stop();
}
else
{
gameArea.clear();
obstacle.update();
gameArea.keyboard();
gamePieceBorder.move();
gamePieceBorder.update();
gamePieceRed.move();
gamePieceRed.update();
}
}
//-----------------------------------------
<html>
<style>
canvas
{
border: 1px solid #d3d3d3;
background-image: url("https://ak0.picdn.net/shutterstock/videos/22492090/thumb/1.jpg");
}
</style>
<body onload = "startGame()">
</body>
</html>
Related
I am very new to coding. I am trying to make a game using java in notepad++. I cant seem to get it so that when the red square (player) hits the purple (TopEdge) the red square will not stop completely but also wont travel through the purple. Like a wall. Right now when the red square hits the purple, you cant move it anymore. I have tried almost everything i could find on the internet. Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8">
<style>
canvas {
border:4px solid #000000;
background-color: #1FB026;
}
</style>
</head>
<body onload="startGame()">
<script>
var player;
var TopEdge;
function startGame() {
player = new component(30, 30, "red", 10, 120);
TopEdge = new component(10000, 300, "purple", 0, -200);
myGameArea.start();
}
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);
}
}
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;
let playerX = this.X + this.speedX;
let playerY = this.Y + this.speedY;
if (playerX >= 0 && this.width + playerX <= this.gamearea.canvas.width)
{
this.X = playerX;
}
if (playerY >= 0 && this.height + playerY <= this.gamearea.canvas.height)
{
this.Y = playerY;
}
}
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 stopY() {
player.speedY = 0;
}
function updateGameArea() {
if (player.crashWith(TopEdge)) {
} else {
myGameArea.clear();
TopEdge.update();
player.x += player.speedX;
player.y += player.speedY;
player.update();
}
TopEdge.update();
player.speedX = 0;
player.speedY = 0;
if (myGameArea.keys && myGameArea.keys[65]) {player.speedX = -2.5; }
if (myGameArea.keys && myGameArea.keys[68]) {player.speedX = 2.5; }
if (myGameArea.keys && myGameArea.keys[87]) {player.speedY = -2.5; }
if (myGameArea.keys && myGameArea.keys[83]) {player.speedY = 2.5; }
player.newPos();
player.update();
}
</script>
</body>
</html>
The problem starts with your updateGameArea() function.
If your the player crashes with the TopEdge then you do nothing. Your creating a problem with your else-part over there. It will never reach the else like this, so nothing while change, so next time it still won't move and again it will not reach the else.....
How about removing the else part. Just check for everything all the time, but don't allow it to move up when it reached the TopEdge.
This should help.
function updateGameArea() {
// I'd prefer these calls at the end of the function block
// but right now your program would start kinda buggy then
myGameArea.clear();
player.newPos();
player.update();
TopEdge.update();
// In default state (nothing pressed) player shouldn't move up or down
player.speedX = 0;
player.speedY = 0;
// If the player does press a key set correct speed/direction
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; }
// Check if player reached the top
// If it did, then it shouldn't be able to climb any higher.
// So even if the player presses the up-button,
// the vertical speed should still not be aloud to change.
if (player.crashWith(TopEdge) && myGameArea.keys[87]) {
player.speedY = 0;
}
// Move the position of the player
player.x += player.speedX; //
player.y += player.speedY;
}
I am trying to finish the main framework of a computer game that I am creating and am trying to implement "scores" or values into it to make it more functional.
I have some basic code that actually works, but not exactly how I want to.
Here is the code that I have been using (all the variables have been declared)
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 600;
this.canvas.height = 480;
//this.canvas.style.cursor = "none"; //hide the original cursor
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 1);
window.addEventListener('mousedown', function (e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
console.log("hello");
});
window.addEventListener('mouseup', function (e) {
myGameArea.x = false;
myGameArea.y = 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.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
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.clicked = function() {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var clicked = true;
if ((mybottom < myGameArea.y) || (mytop > myGameArea.y) || (myright < myGameArea.x) || (myleft > myGameArea.x)) {
clicked = false;
}
return clicked;
}
}
function updateGameArea() {
myGameArea.clear();
if (myGameArea.x && myGameArea.y) {
if (item1.clicked()) {
console.log("red square says hi");
myScore = myScore + 1;
}
if (item2.clicked()) {
console.log("orange square says hi");
}
if (item3.clicked()) {
console.log("yellow square says hi");
}
if (item4.clicked()) {
console.log("green square says hi");
}
if (item5.clicked()) {
console.log("blue square says hi");
}
if (item6.clicked()) {
console.log("purple square says hi");
}
}
scoreDisplay.text = "Score: " + myScore;
scoreDisplay.update();
myGamePiece.update();
item1.update();
item2.update();
item3.update();
item4.update();
item5.update();
item6.update();
itemArea.update();
orderScreen.update();
}
When I click the red square(item1) the score increases, but it doesn't stop until I stop clicking or my mouse is up. I want my code to simply increase the value once per click of the object instead of increasing when the mouse is down.
The logic behind what you want to happen is pretty much this :
JavaScript :
var i = 0;
function addPoint() {
if (document.getElementById("value").value != null) {
document.getElementById("value").value = ++i;
} else { return false }
}
HTML :
<button onclick="addPoint()">+1 Point</button>
<input type="text" id="value" value="0"></input>
If you want a more "complete" approach, you could do this on the JavaScript part :
function addPoint() {
var addValue = parseInt(document.getElementById("value").value, 10);
addValue = isNaN(addValue) ? 0 : addValue;
addValue++;
document.getElementById("value").value = addValue;
}
Use an event listener like you did for the events mousedown
and mouseup:
This will capture every click inside your canvas, not outside.
Define a variable in your myGameArea object:
var myGameArea = {
canvas : document.createElement("canvas"),
clicks : 0, //HERE
start : function() {
this.canvas.width = 600;
this.canvas.height = 480;
...
And then, add the event listener on the start() function:
var myGameArea = {
canvas : document.createElement("canvas"),
clicks : 0,
start : function() {
this.canvas.width = 600;
this.canvas.height = 480;
//this.canvas.style.cursor = "none"; //hide the original cursor
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 1);
window.addEventListener('mousedown', function (e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
console.log("hello");
});
this.canvas.addEventListener("click",(e)=>{ // Use ES6 arrow function
this.clicks++;
});
...
Take a look at an example:
var myGameArea = {
canvas : document.querySelector("canvas"),
clicks : 0,
start : function(){
this.canvas.addEventListener("click",(e)=>{ // Use ES6 arrow function
this.clicks++;
console.log(`Click+1, now = ${this.clicks}`);
});
}
};
myGameArea.start();
canvas{
background: black;
}
<canvas width="300" height="300"></canvas>
I was putting in practice the HTML Game for the first time.
I managed to get through with my game just having the https://www.w3schools.com/graphics/game_intro.asp as my only guide.
The game is very simple: Random objects (green squares) fall from above. The player (red square) moves right and left. The main goal here in the game is for the player to collect/collide with as many as falling objects. Every time the collision happens with 1 object, the player earns 1 point.
Now, how can i destroy the object(green square) that collides with the player and set 1 point at a time?
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Food Game v1</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-image: linear-gradient(#FFFDF0, white);
}
/* buttons align in center*/
.center {
margin: auto;
width: 90%;
padding: 10px;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myFallenObj_ = []; //array of fallen objects
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 130, 300);
myScore = new component("10px", "Consolas", "black", 100, 345,"text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 300;
this.canvas.height = 350;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0; //if we use an array
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, type) {
this.type = type;
this.width = width;
this.height = height;
this.score = 0;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
if(this.type == "text"){ //check on text object
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.x += this.speedX;
this.y += this.speedY;
}
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((myright < otherleft) || (myleft > otherright) || (mybottom < othertop) || (mytop > otherbottom)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.newPos();
myGamePiece.update();
var width_, minWidth_, maxWidth_;
var x,y;
for (i=0;i<myFallenObj_.length; i++){
if(myGamePiece.crashWith(myFallenObj_[i])){ //if collision happens
myScore.score ++;
//destroy(myFallenObj_[i]);
}
}
myScore.text = "SCORE: " + myScore.score;
//check myGamePiece not go over the left border
if(myGamePiece.x <= 0)
myGamePiece.x = 1;
//check myGamePiece not go over the right border
if(myGamePiece.x > 265)
myGamePiece.x = 260;
myScore.update();
myGameArea.frameNo +=1;
if (myGameArea.frameNo == 1 || everyinterval(150)){
//x = 10;
minWidth_=0;
maxWidth_=300;
width_ = Math.floor(Math.random()*(maxWidth_-minWidth_+1)+minWidth_);
y = - 50;
myFallenObj_.push(new component (30,30,"green", width_, y));
}
for (i=0; i<myFallenObj_.length; i++){
myFallenObj_[i].x +=0;
myFallenObj_[i].y +=1;
myFallenObj_[i].update();
}
}
function everyinterval(n){
if((myGameArea.frameNo /n) % 1 == 0)
return true;
return false;
}
function moveleft() {
myGamePiece.speedX = - 2;
}
function moveright() {
myGamePiece.speedX = 2;
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
</script>
<div class="center">
<button onmousedown="moveleft()" onmouseup="clearmove()" ontouchstart="moveleft()">LEFT</button>
<button onmousedown="moveright()" onmouseup="clearmove()" ontouchstart="moveright()">RIGHT</button><br><br>
</div>
</body>
</html>
What i've done so far is to apply that collision and count the score, but the score counts for as long as the red and green keep touching themselves repeatedly (which is wrong).
Any suggestions are more than welcome, thx!
Add scorable attribute to your component:
function component(...) {
...
this.scorable = true;
...
}
Then use the attribute to flag if it still scorable, if not skip:
for (i=0;i<myFallenObj_.length; i++){
if(myGamePiece.crashWith(myFallenObj_[i]) && myFallenObj_[i].scorable){ //if collision happens
myScore.score ++;
myFallenObj_[i].scorable = false;
//destroy(myFallenObj_[i]);
}
}
Thanks to #ACD i solved half of my problem concerning the points' count.
The other half of my answer was how to handle my (green) component: get the point when the green component crashes on to the red one and then disappears.
Well, i couldn't handle properly the destroy attribute of my object (in this case my component). Too much JS with Unity, i suppose :p . I don't know if there is such an attribute for the HTML Canvas' philosophy. To "apply" in a way the destroy attribute to my problem here (as to make my green component to disappear from the canvas) i had to create an "illusion" that came to my mind at first. Basically, playing with the component's positioning around the canvas.
Mainly, i had to set a variable var garbagePOS = 2000; //any possible measure out of my canvas size.
And then i set the position x of my crashed green component into its new positioning equals 2000 (visually, out of my content) myFallenObj_[i].x = garbagePOS; And just like that it creates the illusion. Probably, not an ideal solution. However it works fine for me at the moment. Any more suggestions for the above?
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
I created a game using Javascript. It is a game where a circle which can be controlled by the mouse, has to navigate through moving obstacles similar to a maze. When the circle hits an obstacle, the game should stop.
When i tried the same game but with one obstacle, it worked. But after adding more lines of code to create more obstacles, the circle and the obstacle doesn't appear in the output. Also, the crashWith function isn't being called when the circle hits the obstacle.
Here is the code:
<!DOCTYPE html>
<html>
<style>
canvas {
border:1px solid #000000;
background-image: url("https://data.whicdn.com/images/223851992/large.jpg");
}
</style>
<body onload="begin()">
<script>
var gamePiece;
var gameObstacle = [];
function begin(){
gameArea.start();
gamePiece = new piece(10, "white", 20, 135);
}
var gameArea = {
canvas : document.createElement("canvas"),
start : function(){
this.canvas.width = 480;
this.canvas.height = 270;
this.canvas.style.cursor= 'none';
this.context = this.canvas.getContext("2d");
document.body.insertBefore( this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGame , 10); //for each frame
window.addEventListener('mousemove', function(n){
gameArea.x = n.pageX;
gameArea.y = n.pageY;
});
},
clear : function(){
this.context.clearRect(0,0, this.canvas.width, this.canvas.height);
},
stop : function(){
clearInterval(this.interval);
}
}
function eachInterval(e){
if((gameArea.frameNo / e) % 1 == 0)
return true;
else
return false;
}
//for circle
function piece (radius, color, x, y){
this.radius = radius;
this.speedx = 0;
this.speedy =0;
this.x = x;
this.y = y;
this.update = function(){
pieceContext = gameArea.context;
pieceContext.beginPath();
pieceContext.arc( this.x, this.y, this.radius, 0, 2 * Math.PI);
pieceContext.fillStyle = color;
pieceContext.fill();
}
this.newPlace = function(){
this.x += this.speedx;
this.y += this.speedy;
}
}
//for obstacle
function obstacle (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(){
obstacleContext = gameArea.context;
obstacleContext.fillStyle = color;
obstacleContext.fillRect(this.x, this.y, this.width, this.height);
}
this.newPlace = function(){
this.x += this.speedx;
this.y += this.speedy;
}
//check crash
this.crashWith = function(gamePiece){
var collide = true;
var otherleft = this.x;
var otherright = this.x + (this.width);
var othertop = this.y;
var otherbottom = this.y + (this.height);
var circleBottom = gamePiece.y + (gamePiece.radius);
var circleTop = gamePiece.y;
var circleLeft = gamePiece.x;
var circleRight = gamePiece.x + (gamePiece.radius);
if ((circleBottom < othertop) || (circleTop > otherbottom) || (circleRight < otherleft) || (circleLeft > otherright)) {
collide = false;
}
return collide;
}
}
function updateGame(){
var x,y;
for(i=0 ; i<gameObstacle.length ; i++){
if (gameObstacle[i].crashWith(gamePiece)){
gameArea.stop();
return;
}
}
gameArea.clear();
gameArea.frameNo +=1 ;
if(gameArea.frameNo == 1 || eachInterval(150)){
x = gameArea.canvas.width;
y = gameArea.canvas.height - 200;
gameObstacle.push(new obstacle(10, 200, "grey", x, y));
}
for(i=0 ; i<gameObstacle.length ; i++){
gameObstacle[i].x -= 1;
gameObstacle[i].update();
}
gameObstacle.x -= 1;
//giving co ordinates of cursor to game piece
gamePiece.x = gameArea.x;
gamePiece.y = gameArea.y;
gamePiece.update();
gamePiece.newPlace();
}
</script>
</body>
</html>