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> 🐺
Related
After the element or game-piece collides with the wall it stops moving. How can i reset the collision detection so that after the game-piece collides with the wall it is still able to move? Also after the game-piece collides with the ground it stops moving to. So how can i reset that collision detection so that it can move after colliding with the wall?
var myGamePiece;
var myObstacle;
var e = e || window.event;
var speed = 3;
var gravity = 0.05;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myObstacle = new component(10, 200, "green", 300, 120);
myGameArea.start();
myGameArea.gravityPhysics();
}
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);
},
gravityPhysics: function() {
myGamePiece.speedY = -speed;
},
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.hitBottom();
};
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;
};
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
if (
myGameArea.canvas.height - this.height &&
myGamePiece.key == 38
) {
this.y = this.speedY;
}
this.gravitySpeed = 0; // reset?
}
};
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
console.log("crash");
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y -= myGamePiece.speedY;
myGamePiece.update();
}
if (
myGameArea.gravityPhysics() &&
e.keyCode == document.addEventListener("keydown")
) {
myGamePiece.speedY = gravity - 10;
e.keyCode = true;
}
}
document.onkeydown = checkKeyD;
document.onkeyup = gravityPhysics;
function checkKeyD(e) {
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;
}
}
if ((e = e || (window.event && window.event == false))) {
myGamePiece.speedY -= gravity;
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
When the component or square touches the bottom of the canvas and I press the up arrow afterwards it collides with the bottom, every jump the component jumps when I press the up arrow it jumps upwards less and less until the component eventually does not jump at all. But the component at the same time moves left and right perfectly still when this problem occurs.
I am controlling the square with the arrow keys and it is the player for this platform game that i am creating and i have no clue how i can change it.
var myGamePiece;
var platformWidth = 500;
var platformX = 0;
var platformY = 250;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 10, 120);
}
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, 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;
if (myGameArea.canvas.height - this.height && myGamePiece.key == 38) {
this.y = this.speedY;
}
}
};
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {
myGamePiece.speedX = -5;
}
if (myGameArea.key && myGameArea.key == 39) {
myGamePiece.speedX = 5;
}
if (myGameArea.key && myGameArea.key == 38) {
myGamePiece.speedY = -5;
} else {
myGamePiece.speedY = 5;
}
if (myGameArea.key && myGameArea.key == 40) {
myGamePiece.speedY = 5;
}
myGamePiece.newPos();
myGamePiece.update();
}
startGame();
Did you forget to reset the gravity speed?
this.hitBottom = function() {
// ...
if (this.y > rockbottom) {
// ...
this.gravitySpeed = 0; // reset?
}
};
var myGamePiece;
var platformWidth = 360;
var platformX = 0;
var platformY = 120;
function startGame() {
myGameArea.start();
myGamePiece = new Component(12, 12, "red", 10, 10);
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = platformWidth;
this.canvas.height = platformY;
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;
});
},
fill: function(color) {
this.context.save();
this.context.fillStyle = color;
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.restore();
},
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;
if (myGameArea.canvas.height - this.height && myGamePiece.key == 38) {
this.y = this.speedY;
}
this.gravitySpeed = 0; // reset?
}
};
}
function updateGameArea() {
myGameArea.fill('#DE7');
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key) {
switch (myGameArea.key) {
case 37: // left arrow
myGamePiece.speedX = -5;
break;
case 38: // up arrow
myGamePiece.speedY = -5;
break;
case 39: // right arrow
myGamePiece.speedX = +5;
break;
case 40: // down arrow
default:
myGamePiece.speedY = +5;
}
}
myGamePiece.newPos();
myGamePiece.update();
}
startGame();
body {
background: #000;
}
Here is another approach using classes, you can clean up the vector math, by using actual vector classes e.g. Victor.js.
const main = () => {
new GravityGame({
width : 360,
height : 180,
refreshRate : 20
}).start();
}
class AbstractGameClient {
constructor(options) {
this.refreshRate = options.refreshRate
this.view = new GameArea({
width : options.width,
height : options.height
})
}
update() {
this.view.update()
}
start() {
let self = this
self.intervalId = setInterval(function() { self.update() }, self.refreshRate)
return self
}
stop() {
if (self.intervalId) {
clearInterval(self.intervalId)
}
}
}
class GravityGame extends AbstractGameClient {
constructor(options) {
super(options)
let myGamePiece = new Component({
width : 12,
height : 12,
color : 'red'
})
this.view.addComponent(myGamePiece)
}
}
class GameArea {
constructor(options) {
let self = this
self.canvas = document.createElement('canvas')
self.width = options.width
self.height = options.height
self.key = null
self.components = []
self.addListeners()
self.render()
}
render() {
let self = this
self.canvas.width = self.width
self.canvas.height = self.height
self.context = self.canvas.getContext('2d')
document.body.insertBefore(self.canvas, document.body.childNodes[0])
}
addComponent(component) {
this.centerComponent(component)
this.components.push(component)
}
addListeners() {
let self = this;
window.addEventListener('keydown', function(e) {
self.key = e.keyCode;
});
window.addEventListener('keyup', function(e) {
self.key = false;
});
}
fill(color) {
this.context.save();
this.context.fillStyle = color;
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.restore();
}
clear() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
update() {
let self = this
let speed = { x : 0, y : 0 }
if (self.key) {
switch (self.key) {
case 37: // left arrow
speed.x = -5;
break;
case 38: // up arrow
speed.y = -5;
break;
case 39: // right arrow
speed.x = +5;
break;
case 40: // down arrow
default:
speed.y = +5;
}
}
self.fill('#DE7')
self.components.forEach(component => {
component.speed.x = speed.x
component.speed.y = speed.y
component.reposition(self.context)
component.redraw(self.context)
})
}
centerComponent(component) {
let xOffset = Math.floor((this.canvas.width / 2) - component.width / 2)
let yOffset = Math.floor((this.canvas.height / 2) - component.height / 2)
component.position = { x : xOffset, y : yOffset }
}
};
class Component {
constructor(options) {
let self = this
self.width = options.width
self.height = options.height
self.position = options.position
self.color = options.color
self.type = options.type
self.speed = { x : 0, y : 0 }
self.gravity = { x : 0, y : 0.05 };
self.acceleration = { x : 0, y : 0 };
}
redraw(context) {
context.fillStyle = this.color;
context.fillRect(this.position.x, this.position.y, this.width, this.height);
}
reposition(context) {
let self = this
// Increase acceleration
self.acceleration.x += self.gravity.x;
self.acceleration.y += self.gravity.y;
// pos + speed + acceleration
self.position.x += self.speed.x + self.acceleration.x;
self.position.y += self.speed.y + self.acceleration.y;
self.checkBounds(context);
}
checkBounds(context) {
let self = this
let rockbottom = context.canvas.height - this.height
if (self.position.y > rockbottom) {
self.position.y = rockbottom
if (context.canvas.height - self.height && self.key == 38) {
self.position.y = self.speed.y
}
self.acceleration = { x : 0, y : 0 } // reset
}
}
}
main();
body {
background: #000;
}
I need help finishing a function that shoots bullets after pressing 'space'.
I tried using these
var b = new bullet();
var bullets = []
bullets.push(b)
Then a for loop like this:
for (var i = 0; i < 6; i++) {
but I cant get it to work. Basically a function that every time a bullet is made, it is stored in an array then space loops through the array making new bullets on space press.
fiddle: https://jsfiddle.net/tmanrocks999/7mLpo8uj/652/
code:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:4px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var endGoalPiece;
var myEnemy1;
var bullet;
var myEnemy1Hp = 10;
var damage = 1;
var playerExp = 0;
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;
}
}
}
function jump() {
myGamePiece.gravitySpeed=-1;
}
}
function shootGun(){
bullet = new component(11, 5, "blue", myGamePiece.x+27 , myGamePiece.y+13 );
bullet.newPos();
bullet.speedX=1;
}
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();
bullet.newPos();
bullet.update();
}
</script>
<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><br> / <span id = "playerMaxExp">100</span>
</body>
</html>
I expect on space press for bullets to keep being created by looping through the array but at the moment after space press only 1 bullet is made and position is reset every time you press space ( I know why this is I don't need it explained).
How can I get the illusion of a shooter.
Take a look at this code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>STACKOVERFLOW</title>
<style>
canvas {
border: 4px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<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><br> / <span id = "playerMaxExp">100</span>
<script>
var myGamePiece;
var endGoalPiece;
var myEnemy1;
var bullets = [];
var myEnemy1Hp = 10;
var damage = 1;
var playerExp = 0;
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;
}
}
function jump() {
myGamePiece.gravitySpeed = -1;
}
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();
}
</script>
</body>
</html>
Codepen
I'm new to programming and I tried to make a game. You move a red block and when you hit a green block the you go back to (0,0) and the green block goes to a random location.
Now my question is how do I put a score counter in the game when I hit the green block that it counts +1.
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(40, 40, "red", 0, 0);
myObstacle = new component(40, 40, "green", Math.floor((Math.random() *
560) +
0), Math.floor((Math.random() * 360) + 0));
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.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)) {
return startGame();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
if (myGamePiece.x >= 580) {
myGamePiece.x -= 20;
}
if (myGamePiece.x <= -20) {
myGamePiece.x += 20;
}
if (myGamePiece.y <= -20) {
myGamePiece.y += 20;
}
if (myGamePiece.y >= 380) {
myGamePiece.y -= 20;
}
}
}
function anim(e) {
if (e.keyCode == 39) {
myGamePiece.speedX = 1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 37) {
myGamePiece.speedX = -1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 40) {
myGamePiece.speedY = 1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 38) {
myGamePiece.speedY = -1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 32) {
myGamePiece.speedY = 0;
myGamePiece.speedX = 0;
}
}
document.onkeydown = anim;
window.onload=startGame();
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<button onmousedown="anim(e)" onmouseup="clearmove()" ontouchstart="moveup()">Start</button>
<br><br>
<p>press start to start
<br> use the buttons ↑ ↓ → ← on your keyboard to move stop with the space</p>
Changes
Added an <output> tag to display score.
Redefined event handlers/listeners
Details on changes are commented in demo
Demo
// Reference output#score
var score = document.getElementById('score');
// Declare points
var points = 0;
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(40, 40, "red", 0, 0);
myObstacle = new component(40, 40, "green", Math.floor((Math.random() *
560) +
0), Math.floor((Math.random() * 360) + 0));
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.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)) {
// Convert points to a real number
points = parseInt(points, 10);
// Increment points
points++;
// Set output#score value to points
score.value = points;
return startGame();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
if (myGamePiece.x >= 580) {
myGamePiece.x -= 20;
}
if (myGamePiece.x <= -20) {
myGamePiece.x += 20;
}
if (myGamePiece.y <= -20) {
myGamePiece.y += 20;
}
if (myGamePiece.y >= 380) {
myGamePiece.y -= 20;
}
}
}
function anim(e) {
if (e.keyCode == 39) {
myGamePiece.speedX = 1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 37) {
myGamePiece.speedX = -1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 40) {
myGamePiece.speedY = 1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 38) {
myGamePiece.speedY = -1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 32) {
myGamePiece.speedY = 0;
myGamePiece.speedX = 0;
}
}
/* Set on click handler
|| When event occurs call startGame() / exclude
|| parenthesis
*/
document.onclick = startGame;
/* Register keydown event
|| When event occurs call anim() / exclude parenthesis
*/
document.addEventListener('keydown', anim, false);
/* When a callback is a named function / exclude the
|| parenthesis
*/
window.onload = startGame;
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
button {
font: inherit;
}
<br><br>
<button id='start'>Start</button>
<br><br>
<label for='score'>Score: </label>
<output id='score'>0</output>
<br><br>
<p>Click <kbd>Start</kbd> button</p>
<p>Use the buttons ↑ ↓ → ← on your keyboard to move stop with the spacebar.</p>
add
var chrashed = 0;
and use
if (myGamePiece.crashWith(myObstacle)) {
crashed++;
showCrashed;
return startGame();
}
https://jsfiddle.net/mplungjan/m4w3ahj1/
I am working on Browser game, and I wanted to make map where you can move around, fight with mobs, buy some stuff, but only map. Everything else will be in different pages.
So I made map with multiple images which are in loop.
It reads value world, x and y from database. I have made it work with ajax so the page doesnt refresh every time you move, but I wanted to make this map using Canvas.
$ystart = $y - 2;
$ymax = $y + 2;
$xstart = $x - 3;
$xmax = $x + 3;
for($y=$ystart;$y<=$ymax;$y++){
echo "<tr>";
for($x=$xstart;$x<=$xmax;$x++){
// echo "<td><img src=images/map/day/".$x."_".$y.".jpg width=100 height=100 border=0></td>\n";
if($x==$posx and $y==$posy){
echo "<td background=images/map/world_".$world."/".$y."_".$x.".jpg><img src=images/char.png width=100 height=100 border=0></td>";
} else{
echo "<td><img src=images/map/world_".$world."/".$y."_".$x.".jpg width=100 height=100 border=0></td>";
}
}
echo "</tr>";
}?>
I have done this so far
body {
margin: 0;
}
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<body onload="startGame()">
<script>
var myGamePiece;
var myUpBtn;
var myDownBtn;
var myLeftBtn;
var myRightBtn;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myUpBtn = new component(30, 30, "blue", 50, 10);
myDownBtn = new component(30, 30, "blue", 50, 70);
myLeftBtn = new component(30, 30, "blue", 20, 40);
myRightBtn = new component(30, 30, "blue", 80, 40);
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('mousedown', function(e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
window.addEventListener('mouseup', function(e) {
myGameArea.x = false;
myGameArea.y = false;
})
window.addEventListener('touchstart', function(e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
window.addEventListener('touchend', function(e) {
myGameArea.x = false;
myGameArea.y = false;
})
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.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;
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.x && myGameArea.y) {
if (myUpBtn.clicked()) {
myGamePiece.y -= 1;
}
if (myDownBtn.clicked()) {
myGamePiece.y += 1;
}
if (myLeftBtn.clicked()) {
myGamePiece.x += -1;
}
if (myRightBtn.clicked()) {
myGamePiece.x += 1;
}
}
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && (myGameArea.key == 37 || myGameArea.key == 65)) {
myGamePiece.speedX = -1;
}
if (myGameArea.key && (myGameArea.key == 39 || myGameArea.key == 68)) {
myGamePiece.speedX = 1;
}
if (myGameArea.key && (myGameArea.key == 38 || myGameArea.key == 87)) {
myGamePiece.speedY = -1;
}
if (myGameArea.key && (myGameArea.key == 40 || myGameArea.key == 83)) {
myGamePiece.speedY = 1;
}
myGamePiece.newPos();
myUpBtn.update();
myDownBtn.update();
myLeftBtn.update();
myRightBtn.update();
myGamePiece.update();
}
</script>
</body>
But I can't figure out how to make this background loop in canvas based on x and y position and how to make it change when you move.
I'm trying to learn about canvas myself, so I've been browsing through these questions. I thought yours would be a fun exercise to try.
Basically, I'm creating an object, and moving it at each iteration. I will constantly check the x position of my object. And depending on its value, I can change the background image.
Try this and see for yourself. Try moving your right arrow key and then left arrow key. You will notice the background image changes.
var canvas = document.getElementById("my-canvas");
var ctx = canvas.getContext("2d");
canvas.style.backgroundImage = "url('http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-26.jpg')";
function hero(x, y) {
this.x = x;
this.y = y;
this.moveLeft = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.x -= 5;
drawHero(this.x, this.y);
};
this.moveRight = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.x += 5;
drawHero(this.x, this.y);
};
this.moveUp = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.y -= 5;
drawHero(this.x, this.y);
}
this.moveDown = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.y += 5;
drawHero(this.x, this.y);
}
}
function drawHero(x,y) {
ctx.fillStyle = "red";
ctx.fillRect(x, y, 10, 10);
}
var hero1 = new hero(40, 40);
ctx.fillStyle = "red";
ctx.fillRect(40, 40, 10, 10);
window.addEventListener("keydown", function(event) {
if (event.keyCode == 38) {
hero1.moveUp();
}
else if (event.keyCode == 37) {
hero1.moveLeft();
}
else if (event.keyCode == 39) {
hero1.moveRight();
}
else {
hero1.moveDown();
}
});
setInterval(function() {
if (hero1.x <= 100) {
canvas.style.backgroundImage = "url('http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-26.jpg')";
}
else if (hero1.x > 100 && hero1.x <= 200) {
canvas.style.backgroundImage = "url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRi2F1v1PXpOEYScFCbvmsV-74C573z8tFBvIPXwDO8d1KImpJ09Q')";
}
else {
canvas.style.backgroundImage = "url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSOSNoN1aLzWvpwrENvqPb4tKgzfeeqlMsUeC0fjdGABXXLdLIo')";
}
},50);
#my-canvas {
border: 1px solid black;
}
<canvas id="my-canvas" width="400" height="400"></canvas>