How to make object scroll through HTML5 canvas? - javascript

I've been trying to make objects scroll through the canvas, like when it goes down, it will come out of the top. I have got it working for the bottom and right sides, but it just gets stuck on the left and top side.
Here is what the code looks like in action
http://output.jsbin.com/gavuqo/
Here is my javascript code:
var count = 1;
var myGamePiece;
var myObstacle;
var myHealth;
var myScore;
function startGame() {
myGamePiece = new component(40, 40, "http://www.link", 10, 120, "image");
myObstacle = new component(60, 60, "http://www.link", 300, 120, "image");
myHealth = new component(60, 60, "http://www.link", 300, 100, "image");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 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, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.width = width;
this.height = height;
this.angle = Math.floor(Math.random() * 360) + 0 ;
this.speed = 1;
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() {
if( this.x<=0 || this.x>=600){this.x = -this.speed * Math.sin(this.angle);}else{ this.x += this.speed * Math.sin(this.angle);
}
if( this.y<=0 || this.y>=400) {this.y = -this.speed * Math.cos(this.angle);}else{
this.y += this.speed * Math.cos(this.angle);}
}
//myObstacle.newPos();
this.newPosmain = 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 ((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
return crash;
};
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle) && count==1) {
myObstacle = new component(60, 60, "http://www.link", 300, 120, "image");
count++;
myGamePiece = new component(80, 80, "http://www.link", 10, 120, "image");
} else {
myGameArea.clear();
myObstacle.update();
//myObstacle.wallBounce();
myObstacle.newPos();
myHealth.update();
myHealth.newPos();
//myHealth.wallBounce();
myGamePiece.newPosmain();
myGamePiece.update();
}
if(myGamePiece.crashWith(myObstacle) && count==2){
myObstacle = new component(60, 60, "http://www.link", 300, 120, "image");
myGamePiece = new component(100, 100, "http://www.link", 10, 120, "image");
count++;
}
if(myGamePiece.crashWith(myObstacle) && count==3){
myGamePiece = new component(500, 500, "#", 0, 0, "image");
myeGameArea.stop();
document.body.style.backgroundImage = "url('#')";
count=0;
}
if(myGamePiece.crashWith(myHealth) && count==1){
myGamePiece = new component(100, 100, "http://www.link", 10, 120, "image");
count=0;
count--;
}
if(myGamePiece.crashWith(myHealth) && count==2){
myGamePiece = new component(40, 40, "http://www.link", 10, 120, "image");
count--;
}
if(myGamePiece.crashWith(myObstacle) && count==0){
myObstacle = new component(60, 60, "http://www.link", 300, 120, "image");
myGamePiece = new component(100, 100, "http://www.link", 10, 120, "image");
count++;
}
if(myGamePiece.crashWith(myHealth) && count==0){
myGamePiece = new component(500, 500, "http://example.com", 0, 0, "image");
}
}
function moveup() {
myGamePiece.speedY = -2;
}
function movedown() {
myGamePiece.speedY = 2;
}
function moveleft() {
myGamePiece.speedX = -2;
}
function moveright() {
myGamePiece.speedX = 2;
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}

Simply adjust either the x or y position to be opposite of the exit point. If it exits at the bottom then reset it to top minus diameter of the object without adjusting x, and so forth.
In generic code:
// dia = diameter of object (you may have to use different values for width/height)
if (x < -dia) x = width;
else if (x >= width) x = -dia;
if (y < -dia) y = height;
else if (y >= height) y = -dia;
Example
(click run again to change direction)
var ctx = c.getContext("2d"),
x = c.width * 0.5, y = c.height * 0.5,
dx = Math.max(2, Math.random() * 4),
dy = Math.max(2, Math.random() * 4),
dia = 10;
dx *= Math.random() < 0.5 ? -1 : 1;
dy *= Math.random() < 0.5 ? -1 : 1;
(function loop() {
ctx.clearRect(0,0,c.width,c.height);
ctx.fillRect(x, y, dia, dia);
x += dx;
y += dy;
if (x < -dia) x = c.width;
else if (x >= c.width) x = -dia;
if (y < -dia) y = c.height;
else if (y >= c.height) y = -dia;
requestAnimationFrame(loop)
})()
#c {border:1px solid #999}
<canvas id=c>

Related

How do I change a color of a Html element in a canvas?

I have made a post on this before however, it was not in a canvas, but when you try to apply this to a canvas It gives an error along the lines of Cant change the color of undefined so I thought it was an error of the way I defined it so I would add it to a class then run it as changing the color of all elements in the class, but when I try it the canvas just disappears.. but getting to the point is there an easy way to change the color of a HTML element in a canvas or am I just crazy
Code
var myGamePiece = el.classList.add("class1");
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.interval = setInterval(updateGameArea, 20);
},
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) {
myGamePiece.gravity = n;
}
function Test() {
document.getElementsByClassName("class1").style.background = "yellow";
}
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
.class1 {}
<body onload="startGame()">
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p> Credit To W3Schools.com </p>
<button onclick="test">Click To Change Player's Color</button>
</body>
The code starts with: var myGamePiece = el.classList.add("class1");el is not defined but anyway myGamePiece needs to be a component as created in startGame, it is not an ordinary HTML element.
It is the creation of that component that the color is set. Currently the color is hardcoded as 'red'. To change the color you need to set a variable, let's call it playerColor, and use that in the component creation call rather than 'red'.
You are using function test to set up a color so let's change the test function to do that, but you need to get that color set up before startGame otherwise the canvas will have the incorrect color for the piece (or no set color).
var playersColor = "red"; //the default value if the player doesn't change it
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, playersColor, 10, 120);//use playersColor
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.interval = setInterval(updateGameArea, 20);
},
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) {
myGamePiece.gravity = n;
}
function test() {
playersColor = "yellow";
}
<body>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p> Credit To W3Schools.com </p>
<button onclick="test()">Click To Change Player's Color</button>
<button onclick="startGame();">Click to start the game</button>
</body>
...............................................................................
Although the following errors are not fundamentally what is causing non-changing of the player's color, they contain some coding errors which it might be helpful to point out for the future.
<button onclick="test">Click To Change Player's Color</button>
<script>
function Test() {
document.getElementsByClassName("class1").style.background = "yellow";
</script>
The onclick="test" does nothing - you may be confusing the structure element.onclick = test - which sets which function is run on the element being clicked - with the syntax for the onclick="test();" needed in the button element attributes.
A further error is that the function is called Test, not test. Javascript is case sensitive. Also you need to select the one element with class1, not retrieve a collection of such elements, so you can set its style (if that is useful, is it?).

hit function when hits a enemy makes all bullets disapear

Im trying to make a function that when hitting a enemy makes that bullet in the array disappear.
Ive tried useing pop, slice, shift but i cant get those to work.
the closest thing Ive found is to just make the array empty but it really should be the array -1 or minus that bullet.
js fiddle: https://jsfiddle.net/tmanrocks999/64thbvm3/309/
code:
var myGamePiece;
var endGoalPiece;
var myEnemy1;
var bullets = [];
var myEnemy1Hp = 10;
var myEnemy1Armor = 0;
var damage = 1;
var playerExp = 0;
var playerMaxExp = 10;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, 'red', 0, 240);
endGoalPiece = new component(30, 30, 'black', 450, 240);
myEnemy1 = new component(30, 30, 'green', 200, 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.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.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.color = color;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = this.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.hitTop();
this.hitRight();
this.hitLeft();
this.hitObject();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
}
}
this.hitTop = function() {
var rockTop = 0;
if (this.y < rockTop) {
this.y = rockTop;
}
}
this.hitRight = function() {
var rockRight = myGameArea.canvas.width - this.width;
if (this.x > rockRight) {
this.x = rockRight;
}
}
this.hitLeft = function() {
var rockLeft = 0;
if (this.x < rockLeft) {
this.x = rockLeft;
}
}
function enemyRespawn() {
myEnemy1 = new component(30, 30, "green", 200, 240);
myEnemy1Hp = 10;
document.getElementById('myEnemy1Hp').innerHTML = myEnemy1Hp;
}
this.hitObject = function() {
myGamePiece.update();
var enemy = myEnemy1.x - 11;
if (this.x == enemy) {
myEnemy1Hp = myEnemy1Hp - (damage - myEnemy1Armor);
bullets = [];
document.getElementById('myEnemy1Hp').innerHTML = myEnemy1Hp;
if (myEnemy1Hp <=0) {
myEnemy1Hp = 0;
document.getElementById('myEnemy1Hp').innerHTML = myEnemy1Hp;
playerExp = playerExp+1;
document.getElementById('playerExp').innerHTML = playerExp;
if (playerExp >= playerMaxExp) {
playerExp = 0;
playerMaxExp = playerMaxExp * 1.5;
damage = damage + 1;
document.getElementById('playerExp').innerHTML = playerExp;
document.getElementById('playerMaxExp').innerHTML = playerMaxExp;
}
myEnemy1 = new component(0, 0, 'green', 0, 0);
myEnemy1.update();
setTimeout(enemyRespawn, 5000);
}
}
}
}
function shootGun() {
let bullet = new component(11, 5, 'blue', myGamePiece.x + 27, myGamePiece.y + 13);
bullet.newPos();
bullet.speedX = 1;
bullets.push(bullet);
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {
myGamePiece.speedX = -1;
} //left
if (myGameArea.key && myGameArea.key == 39) {
myGamePiece.speedX = 1;
} //right
if (myGameArea.key && myGameArea.key == 38) {
myGamePiece.gravitySpeed = -1;
} //jump
if (myGameArea.key && myGameArea.key == 32) {
shootGun()
} //shoot gun
//if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }// down
myEnemy1.update();
endGoalPiece.update();
myGamePiece.newPos();
myGamePiece.update();
bullets.forEach((bullet) => {
bullet.newPos()
bullet.update();
});
// bullet.newPos();
// bullet.update();
}
startGame();
canvas {
border: 4px solid #d3d3d3;
background-color: #f1f1f1;
}
<p>use the arrow keys on you keyboard to move the red square.</p>
<span id="myEnemy1Hp">10</span> <br>
<span id="playerExp">0</span> / <span id="playerMaxExp">10</span> 🐺
I expect when the bullet hit the enemy for it to disappear then enemy takes 1 damage. but at the moment this works but if u have more then 1 bullet on the screen all the bullets disappear when 1 hits the enemy. How do i make it current bullet or array = array -1
I believe you are looking for array.splice()
In the context of your hitObject method, the code would look like this:
bullets.splice(bullets.indexOf(this), 1);
Also, there are a ton of notes in my answer to a similar question which you may find useful.
...and here's your updated game:
var myGamePiece;
var endGoalPiece;
var myEnemy1;
var bullets = [];
var myEnemy1Hp = 10;
var myEnemy1Armor = 0;
var damage = 1;
var playerExp = 0;
var playerMaxExp = 10;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, 'red', 0, 240);
endGoalPiece = new component(30, 30, 'black', 450, 240);
myEnemy1 = new component(30, 30, 'green', 200, 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.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.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.color = color;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = this.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.hitTop();
this.hitRight();
this.hitLeft();
this.hitObject();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
}
}
this.hitTop = function() {
var rockTop = 0;
if (this.y < rockTop) {
this.y = rockTop;
}
}
this.hitRight = function() {
var rockRight = myGameArea.canvas.width - this.width;
if (this.x > rockRight) {
this.x = rockRight;
}
}
this.hitLeft = function() {
var rockLeft = 0;
if (this.x < rockLeft) {
this.x = rockLeft;
}
}
function enemyRespawn() {
myEnemy1 = new component(30, 30, 'green', 200, 240);
myEnemy1Hp = 10;
document.getElementById('myEnemy1Hp').innerHTML = myEnemy1Hp;
}
this.hitObject = function() {
myGamePiece.update();
var enemy = myEnemy1.x - 11;
if (this.x == enemy) {
myEnemy1Hp = myEnemy1Hp - (damage - myEnemy1Armor);
// bullets = []; // replaces all bullets
const index = bullets.indexOf(this)
bullets.splice(index, 1)
document.getElementById('myEnemy1Hp').innerHTML = myEnemy1Hp;
if (myEnemy1Hp <= 0) {
myEnemy1Hp = 0;
document.getElementById('myEnemy1Hp').innerHTML = myEnemy1Hp;
playerExp = playerExp + 1;
document.getElementById('playerExp').innerHTML = playerExp;
if (playerExp >= playerMaxExp) {
playerExp = 0;
playerMaxExp = playerMaxExp * 1.5;
damage = damage + 1;
document.getElementById('playerExp').innerHTML = playerExp;
document.getElementById('playerMaxExp').innerHTML = playerMaxExp;
}
myEnemy1 = new component(0, 0, 'green', 0, 0);
myEnemy1.update();
setTimeout(enemyRespawn, 5000);
}
}
}
}
function shootGun() {
let bullet = new component(11, 5, 'blue', myGamePiece.x + 27, myGamePiece.y + 13);
bullet.newPos();
bullet.speedX = 1;
bullets.push(bullet);
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {
myGamePiece.speedX = -1;
} //left
if (myGameArea.key && myGameArea.key == 39) {
myGamePiece.speedX = 1;
} //right
if (myGameArea.key && myGameArea.key == 38) {
myGamePiece.gravitySpeed = -1;
} //jump
if (myGameArea.key && myGameArea.key == 32) {
shootGun()
} //shoot gun
//if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }// down
myEnemy1.update();
endGoalPiece.update();
myGamePiece.newPos();
myGamePiece.update();
bullets.forEach((bullet) => {
bullet.newPos(); // update and check for collisions
bullet.update();
});
// bullet.newPos();
// bullet.update();
}
startGame();
canvas {
border: 4px solid #d3d3d3;
background-color: #f1f1f1;
}
<p>use the arrow keys on you keyboard to move the red square.</p>
<span id="myEnemy1Hp">10</span> <br>
<span id="playerExp">0</span> / <span id="playerMaxExp">10</span> 🐺

Invert direction of game

I am developing a basic game where the user needs to go through the openings and avoid crashing with the obstacles. My issue now is that the flow of the game is from the bottom to the top, when in fact I need the obstacles to come from the top to the bottom.
What am I missing in the code? Any help is appreciated.
let myObstacles = [];
let myGameArea = {
canvas: document.createElement("canvas"),
frames: 0,
start: function() {
this.canvas.width = 700;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
this.canvas.classList.add('canvasBg');
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);
},
score: function() {
var points = Math.floor(this.frames / 5);
this.context.font = "18px serif";
this.context.fillStyle = "black";
this.context.fillText("Score: " + points, 350, 50);
}
}
class Component {
constructor(width, height, color, x, y) {
this.width = width;
this.height = height;
this.color = color;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
}
update() {
let ctx = myGameArea.context;
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
newPos() {
this.x += this.speedX;
this.y += this.speedY;
}
left() {
return this.x;
}
right() {
return this.x + this.width;
}
top() {
return this.y;
}
bottom() {
return this.y + this.height;
}
crashWith(obstacle) {
return !(
this.bottom() < obstacle.top() ||
this.top() > obstacle.bottom() ||
this.right() < obstacle.left() ||
this.left() > obstacle.right()
);
}
}
function checkGameOver() {
let crashed = myObstacles.some(function(obstacle) {
return player.crashWith(obstacle);
});
if (crashed) {
myGameArea.stop();
}
}
document.onkeydown = function(e) {
switch (e.keyCode) {
case 38: // up arrow
player.speedY -= 1;
break;
case 40: // down arrow
player.speedY += 1;
break;
case 37: // left arrow
player.speedX -= 1;
break;
case 39: // right arrow
player.speedX += 1;
break;
}
};
function updateObstacles() {
for (i = 0; i < myObstacles.length; i++) {
myObstacles[i].y += -3;
myObstacles[i].update();
}
myGameArea.frames += 1;
if (myGameArea.frames % 60 === 0) {
let x = myGameArea.canvas.width;
let y = myGameArea.canvas.height;
let minWidth = 20;
let maxWidth = 200;
let width = Math.floor(
Math.random() * (maxWidth - minWidth + 1) + minWidth
);
var minGap = 70;
var maxGap = 200;
var gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
myObstacles.push(new Component(width, 10, "green", 0, y));
myObstacles.push(
new Component(y-width-gap, 10, "green", width+gap, y)
);
}
}
document.onkeyup = function(e) {
player.speedX = 0;
player.speedY = 0;
};
function updateGameArea() {
myGameArea.clear();
player.newPos();
player.update();
updateObstacles();
checkGameOver();
myGameArea.score();
};
myGameArea.start();
let player = new Component(30, 30, "red", 0, 110);
I got it to work by changing 3 things in your updateObstacles function.
First, change myObstacles[i].y += -3 to myObstacles[i].y += 3
Second, change let y = myGameArea.canvas.height to let y = 0
Third, change
new Component(y-width-gap, 10, "green", width+gap, y)
to
new Component(x-width-gap, 10, "green", width+gap, y)
Full code:
function updateObstacles() {
for (i = 0; i < myObstacles.length; i++) {
myObstacles[i].y += 3;
myObstacles[i].update();
}
myGameArea.frames += 1;
if (myGameArea.frames % 60 === 0) {
let x = myGameArea.canvas.width;
let y = 0;
let minWidth = 20;
let maxWidth = 200;
let width = Math.floor(
Math.random() * (maxWidth - minWidth + 1) + minWidth
);
var minGap = 70;
var maxGap = 200;
var gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
myObstacles.push(new Component(width, 10, "green", 0, y));
myObstacles.push(
new Component(x-width-gap, 10, "green", width+gap, y)
);
}
}
Example jsfiddle

Canvas with HTML and JavaScript

In w3schools there is a basic game and I can't figure out how to make the piece or object a circle. I'm so confused and have tried everything but it didn't work. How can I use fill circle or another method for this? I'm new to canvas.
<!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;
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.interval = setInterval(updateGameArea, 20);
},
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) {
myGamePiece.gravity = n;
}
</script>
<br>
<button onmousedown="accelerate(-0.2)"
onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Use the ACCELERATE button to stay in the air</p>
<p>How long can you stay alive?</p>
</body>
</html>
Change your function component() and startGame() to this one.
You can draw cirlce with arc method.
Details: https://www.w3schools.com/tags/canvas_arc.asp
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120, "player");
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40,
"text");
myGameArea.start();
}
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;
ctx.fillStyle = color;
if (this.type == "text") { // text
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else if (this.type == "player") { // player
ctx.beginPath();
ctx.arc(this.x, this.y, 35,0,2*Math.PI);
ctx.fill();
ctx.stroke();
} else { // wall
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;
}
}

Making Squares Move?

I am trying to make the divs "ySpeed(1)" and "ySpeed(-1)" make myGamePiece move up and down, and eventually, left to right. I made two functions called movePieceUp and movePieceDown. I do not know why the functions are not working correctly. Know a way I can make myGamePiece work correctly?
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 2;
this.speedY = 2;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
this.color = color;
this.update = function() {
random = Math.floor((Math.random() * 200) + 1);
random2 = Math.floor((Math.random() * 200) + 1);
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
randcolor = getRandomColor();
ctx = myGameArea.context;
if (this.type == "image") {
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
} else {
ctx.fillStyle = randcolor;
ctx.fillRect(random, random2, 50, 50);
}
this.x = random;
this.y = random2;
this.width = 50;
this.height = 50;
this.color = randcolor;
}
}
function component2(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 2;
this.speedY = 2;
this.x = x;
this.y = y;
this.gravity = 2;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
if (this.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.x + this.speedX;
this.y = this.y + this.speedY;
//removed hitting rock bottom because the background and other pieces will be off screen.
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
board = 1;
}
}
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 startGame() {
random = Math.floor((Math.random() * 100) + 1);
random2 = Math.floor((Math.random() * 100) + 1);
square = new component(50, 50, "green", random, random2);
myGamePiece = new component2(30, 40, "greenhorn.gif", 220, 120);
enemyPiece2 = new component(50, 50, "Trump1.jpg", random, random2, );
myGameArea.start();
return square
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 450;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 1000);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function updateGameArea() {
myGameArea.clear();
square.update();
myGamePiece.update();
enemyPiece2.update();
}
function movePieceUp() {
myGamePiece.ySpeed(1);
myGamePiece.speedY = 2;
}
function movePieceDown() {
myGamePiece.ySpeed(-1);
myGamePiece.speedX = 2;
}
document.getElementById("start").addEventListener('click', startGame);
document.getElementById("ySpeed(1)").addEventListener('click', movePieceUp);
document.getElementById("ySpeed(-1)").addEventListener('click', movePieceDown);
<p> Click Start Game to play </p>
<div id="start">Start Game</div>
<div id="hi">Hi</div>
<div id="ySpeed(1)">UP</div>
</p>
<div id="ySpeed(-1)">DOWN</div>
You need to be declaring your myGamePiece variable in a place that makes it accessibly by the functions using it. Either make it 'global' by declaring it outside and before the function calls, or pass the variable to the appropriate functions as a parameter.

Categories