First time posting here, and first time creating a game in Javascript.
I'm trying to create collision between two objects in my game, a bullet and an enemy, but for now, just trying to make something happen with just the bullet, when it reaches the top of the screen.
When I press E, this happens:
if (69 in keysDown && timer == 0) //E
{
var newbullet = Object.create(bullet);
newbullet.posx = ship.playerx;
newbullet.posy = ship.playery;
projectiles.push(newbullet);
ship.shoot = true;
}
The bullet then moves upwards as it is stated in its update function.
I'm running this function constantly in my game loop, which checks for collisions, and that looks like this:
function Collision()
{
for (i = 0; i <= projectiles.length; i++)
{
if (bullet.posy < 0 )
{
ctx.fillText("HIT" , 160, 340);
ship.health -= 1;
}
}
}
but it doesn't work. I thought of substituting "bullet.posy" with "projectiles[i].posy, but it ends up saying that projectiles[i] is undefined.
projectiles is a global array.
var projectiles=[];
This is bullet:
var bullet =
{
posx:0,
posy:0,
speed: 10,
power: 2,
draw: function()
{
ctx.fillStyle = "rgb(200,100,0)";
ctx.beginPath();
ctx.rect(((this.posx - 5)), (this.posy - 30), 10, 25);
ctx.closePath();
ctx.fill();
},
setup: function(ax, ay)
{
this.posx = ax;
this.posy = ay;
},
update: function()
{
this.posy -= this.speed;
}
};
Any help or advice?
Here is the link, if you wish to try it out E to shoot.
Thank you.
bullet? What is the value ofprojectiles? Does the value ofbullet.posychange?var newbullet = Object.create(bullet);tovar newbullet = {};or maybevar newbullet = bullet;would be better. Object.create() expects a prototype, not an object literal, to be passed in.