Im building an online multiplayer game where you can click on tiles to move to them. The tiles have an x and z position.
I dont know how to reset the clearInterval if a player clicks another tile in socket.io. Right now it doubles the speed because it duplicates the setInterval I guess and if I try to clearInterval at the beginning it seems not to target the old setInterval. I tried to bind the setInterval to the player[socket.id] object but got a Maximum call stack size exceeded error then.
How do I clear this specific setInterval for the player so it hasnt 2 setIntervals when I click a second tile while moving?
index.js (server)
players[socket.id] = {
x: 0,
z: 0,
xTo:0,
zTo:0,
isMoving: false,
playerId: socket.id,
name: name,
room: 'lobby'
};
//when client clicks on a tile
socket.on('moveRequest', function(pos) {
//set clicked tile x/z to player entity
players[socket.id].xTo = pos[0];
players[socket.id].zTo = pos[2];
//only continiue if clicked tile is different from current tile
if (players[socket.id].x !== players[socket.id].xTo) {
//get direction left/right
var xDiff = players[socket.id].xTo - players[socket.id].x;
var xDirection = 'none';
if (xDiff > 0) {
console.log('player wants to move right');
xDirection = 'right';
} else {
console.log('player wants to move left');
xDirection = 'left';
}
//if there is wanted movement
if (xDirection !== 'none') {
//setInterval 60fps
const moveInterval = setInterval(function() {
//if direction is right and players current position is smaller then clicked position
if (xDirection == 'right' && players[socket.id].x < players[socket.id].xTo) {
//move player
players[socket.id].x = players[socket.id].x + 0.03;
} else {
//if reached destination clear the interval
xDirection = 'none';
clearInterval(moveInterval);
}
//now send move to all players in room
io.to('game').emit('playerMove', players[socket.id]);
}, 1000 / 60);
}
}
});
Related
I'm making a side scroller game in Javascript and need to implement gravity for my character. For example, the character needs to jump up, jump to the right or jump to the left, then gradually come down just by pressing and releasing the up arrow on its own, or with the left or right arrow keys. Here's my code so far:
var gameChar_x; //refers to the characters x position
var gameChar_y; //refers to the characters y position
var floorPos_y; //refers to the y position of the floor
var isJumping = false;
function draw()
if (isJumping == true && gameChar_y == floorPos_y) {
gameChar_y = gameChar_y - 9.8 //makes the character jump when on the floor
}
if (isJumping == false && gameChar_y != floorPos_y) {
gameChar_y = gameChar_y + 9.8 //makes the character come back down when
the up arrow key is released
function keyPressed()
if (keyCode == UP_ARROW && gameChar_y == floorPos_y) { //jump if character is on the floor
isJumping = true;
}
if (keyCode == UP_ARROW && keyCode == RIGHT_ARROW) {
isJumping = true;
}
if (keyCode == UP_ARROW && keyCode == LEFT_ARROW) {
isJumping = true;
}
What I'd like to happen is when the up arrow is pressed and released, the character jumps up and slowly comes back down to the ground by 1 pixel at a time. Thanks for the help.
You could try using an interval to simulate the animation of the char dropping 1px every 100ms:
// Max height a character can jump
const MAX_JUMP_HEIGHT = 10;
// Current position of the character
let x_position = 0;
let y_position = 0;
// Timer variable
let timer = null;
function render() {
// draw the character on the screen according to the current x_position and y_position
}
function onJump() {
// If we're already jumping, we want to cancel the previous jump timeout so gravity suddenly doesn't double.
if ( timer ) clearInterval( timer );
// Set our current position to max jumping height.
y_position = MAX_JUMP_HEIGHT;
timer = setInterval( function() {
// subtract one pixel from the the current position
y_position--;
// call a render function
render();
// Cancel the interval once we reach 0px jump height.
if ( !y_position ) clearInterval( timer );
}, 100 );
};
You can edit the numbers a bit to get stuff like platforms to work, where 0px y_position will not always be the baseline and w want to use the MAX_HEIGHT as an offset per jump.
I am trying to make a game. The object of the game is to move the square across the screen without hitting a raindrop falling from the roof. How do i make it so that if one of the raindrops enters the square, the square returns to the beginning of the canvas or x =0. Here is the code:
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
var WIDTH = 1000;
var HEIGHT = 700;
var x = 0;
var y = HEIGHT-20;
var xPos = [0];
var yPos = [0];
var speed = [1];
var rainDrops = 50;
var rectWidth = 20;
var rectHeight = 20;
for (var i = 0; i < rainDrops; i++) {
xPos.push(Math.random()* WIDTH);
yPos.push(0);
speed.push(Math.random() * 5);
}
function rainFall () {
window.requestAnimationFrame(rainFall);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (var i = 0; i <rainDrops; i++) {
//Rain
ctx.beginPath();
ctx.arc(xPos[i], yPos[i], 3, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
//Rain movement
yPos[i]+=speed[i];
//Box
ctx.fillStyle = 'red';
ctx.fillRect(x, y, rectWidth, rectWidth);
if (yPos[i] > HEIGHT) {
yPos[i]= 0;
yPos[i]+=speed[0];
}
//This is the part where I need the Help!!!!!!!!!
if (){
x = 0;
}
}
};
//Move Object
function move (e) {
if (e.keyCode === 37) {
ctx.clearRect (0, 0, WIDTH, HEIGHT);
x -=10;
}
if (e.keyCode === 39) {
ctx.clearRect (0, 0, WIDTH, HEIGHT);
x+=10;
}
canvas.width=canvas.width
}
//Lockl Screen
window.addEventListener("keydown", function(e) {
// Lock arrow keys
if( [37,39,].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);
rainFall();
document.onkeydown = move;
window.addEventListener("load", doFirst, false);
Conditional statements
I am never too sure how to answer these types of questions. As you are a beginner I don't want to overwhelm you with code and techniques, but at the same time I don't want to give an answer that perpetuates some bad techniques.
The short answer
So first the simple answer from your code where you wrote
//This is the part where I need the Help!!!!!!!!!
// the test checks the center of the drop
// if drop is greater than > top of player (y) and (&&)
// drop x greater than > left side of player x and (&&) drop is less than <
// right side of player (x + rectWidth) then drop has hit player
if (yPos[i] > y && xPos[i] > x && xPos[i] < x + rectWidth ){
x = 0; // move player back
}
BTW you are drawing the player rectangle for each rain drop. You should move that draw function outside the loop.
The long answer
Hopefully I have not made it too confusing and have added plenty of comments about why I did this and that.
To help keep everything organised I separate out the various elements into their own objects. There is the player, rain, and keyboard handler. This is all coordinated via the mainLoop the is called once a frame (by requestAnimationFrame) and calls the various functions to do all that is needed.
The player object holds all the data to do with the player, and functions to draw and update the player (update moves the player)
The rain object holds all the rain in an array called rain.drops it has functions to draw and update the rain. It also has some functions to randomize a drop, and add new drops.
To test if the rain has hit the player I do it in the rain.update function (where I move the rain) I don`t know what you wanted to happen when the rain hits the player so I just reset the rain drop and added 1 to the hit counter.
I first check if the bottom of the rain drop drop.y + drop.radius is greater than the top of the player if(drop.y + drop.radius >= player.y){
This makes it so we dont waste time checking rain that is above the player.
The I test for the rain in the x direction. The easiest is the test the negative (if the rain is not hitting the player) as the logic is a little simplier.
If the right side of the drop is to the left of the left side of the player, or (use || for or) the left side of the drop is to the right of the right side of the player than the drop can not be hitting the player. As we want the reverse condition we wrap it in a brackets a put a not in front if(! ( ... ) )
The test is a little long so I break it into 2 lines for readability.
// drop is a single rain drop player is the player
if (drop.y + drop.radius >= player.y) {
if ( ! (drop.x + drop.radius < player.x ||
drop.x - drop.radius > player.x + player.width) ) {
// code for player hit by rain in here
}
}
The rain.update function also checks if the rain has hit the bottom of the canvas and resets it if so.
Demo
I copied your code from in the question and modified it.
addEventListener("load",function(){ // you had onload at the bottom after all the code that gets the canvas
// etc. Which kind of makes the on load event pointless. Though not needed
// in this example I have put it in how you can use it for a web page.
// Using onload event lets you put the javascript anywhere in the HTML document
// if you dont use onload you must then only put the javascript after
// the page elements you need eg Canvas.
var canvas = document.getElementById('gameCanvas');
var ctx = canvas.getContext('2d');
ctx.font = "20px arial";
var frameCount = 0; // counts the frames
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var currentMaxDrops = 5; // rain will increase over time
const numberFramesPerRainIncrease = 60 * 5; // long name says it all. 60 frames is one second.
const maxRainDrops = 150; // max number of rain drops
// set up keyboard handler
addEventListener("keydown", keyEvent);
addEventListener("keyup", keyEvent);
requestAnimationFrame(mainLoop); // request the first frame of the animation (get it all going)
//==========================================================================================
// Setup the keyboard input stuff
const keys = { // list of keyboard keys to listen to by name.
ArrowLeft : false,
ArrowRight : false,
}
function keyEvent(event){ // the key event argument event.code hold the named key.
if(keys[event.code] !== undefined){ // is this a key we want
event.preventDefault(); // prevent default browser action
keys[event.code] = event.type === "keydown"; // true if keydown false if not
}
}
//==========================================================================================
const player = { // object for everything to do with the player
x : 0, // position
y : HEIGHT - 20,
width : 20, // size
height : 20,
speed : 4, // speed per frame
color : "red",
showHit : 0, // when this is > 0 then draw the player blue to indicate a hit.
// This counter is counted down each frame so setting its value
// determins how long to flash the blue
hitCount : 0, // a count of the number of drops that hit the player.
status(){ // uses hit count to get a status string
if(player.hitCount === 0){
return "Dry as a bone.";
}
if(player.hitCount < 5){
return "A little damp.";
}
if(player.hitCount < 15){
return "Starting to get wet.";
}
return "Soaked to the core";
},
draw(){ // draw the player
if(player.showHit > 0){
player.showHit -= 1; // count down show hit
ctx.fillStyle = "blue";
}else{
ctx.fillStyle = player.color;
}
ctx.fillRect(player.x,player.y,player.width,player.height);
},
update(){ // this updates anything to do with the player
// Not sure how you wanted movement. You had it so that you move only when key down events
// so I have done the same
if(keys.ArrowLeft){
player.x -= player.speed; // move to the left
keys.ArrowLeft = false; // turn off the key. If you remove this line then will move left while
// the key is down and stop when the key is up.
if(player.x < 0){ // is the player on or past left side of canvas
player.x = 0; // move player back to zero.
}
}
if(keys.ArrowRight){
player.x += player.speed; // move to the right
keys.ArrowRight = false; // turn off the key. If you remove this line then will move right while
// the key is down and stop when the key is up.
if(player.x + player.width >= WIDTH){ // is the player on or past right side of canvas
player.x = WIDTH - player.width; // move player back to inside the canvas.
}
}
}
}
//==========================================================================================
const rain = { // object to hold everything about rain
numberRainDrops : 50,
drops : [], // an array of rain drops.
randomizeDrop(drop){ // sets a drop to random position etc.
drop.x = Math.random() * WIDTH; // random pos on canvas
drop.y = -10; // move of screen a little so we dont see it just appear
drop.radius = Math.random() *3 + 1; // give the drops a little random size
drop.speed = Math.random() * 4 + 1; // and some speed Dont want 0 speed so add 1
return drop;
},
createDrop(){ // function to create a rain drop and add it to the array of drops
if(rain.drops.length < currentMaxDrops){ // only add if count is below max
rain.drops.push(rain.randomizeDrop({})); // create and push a drop. {} creates an empty object that the function
// randomizeDrop will fill with the starting pos of the drop.
rain.numberRainDrops = rain.drops.length;
}
},
draw(){ // draw all the rain
ctx.beginPath(); // start a new path
ctx.fillStyle = 'blue'; // set the colour
for(var i = 0; i < rain.drops.length; i ++){
var drop = rain.drops[i]; // get the indexed drop
ctx.arc(drop.x, drop.y, drop.radius, 0, 2 * Math.PI);
ctx.closePath(); // stops the drops rendered as one shape
}
ctx.fill(); // now draw all the drops.
},
update(){
for(var i = 0; i < rain.drops.length; i ++){
var drop = rain.drops[i]; // get the indexed drop
drop.y += drop.speed; // move down a bit.
if(drop.y + drop.radius >= player.y){ // is this drop at or below player height
// checks if the drop is to the left or right of the player
// as we want to know if the player is hit we use ! (not)
// Thus the next if statement is if rain is not to the left or to the right then
// it must be on the player.
if(!(drop.x + drop.radius < player.x || // is the rigth side of the drop left of the players left side
drop.x - drop.radius > player.x + player.width)){
// rain has hit the player.
player.hitCount += 1;
player.showHit += 5;
rain.randomizeDrop(drop); // reset this drop.
}
}
if(drop.y > HEIGHT + drop.radius){ // is it off the screen ?
rain.randomizeDrop(drop); // restart the drop
}
}
}
}
function mainLoop () { // main animation loop
requestAnimationFrame(mainLoop); // request next frame (don`t need to specify window as it is the default object)
ctx.clearRect(0, 0, WIDTH, HEIGHT);
frameCount += 1; // count the frames
// when the remainder of frame count and long name var is 0 increase rain drop count
if(frameCount % numberFramesPerRainIncrease === 0){
if(currentMaxDrops < maxRainDrops){
currentMaxDrops += 1;
}
}
rain.createDrop(); // a new drop (if possible) per frame
rain.update(); // move the rain and checks if the player is hit
player.update(); // moves the player if keys are down and check if play hits the side of the canvas
player.draw(); // draw player
rain.draw(); // draw rain after player so its on top.
ctx.fillStyle = "black";
ctx.fillText("Hit " + player.hitCount + " times.",5,20);
ctx.setTransform(0.75,0,0,0.75,5,34); // makes status font 3/4 size and set position to 5 34 so I dont have to work out where to draw the smaller font
ctx.fillText(player.status(),0,0); // the transform set the position so text is just drawn at 0,0
ctx.setTransform(1,0,0,1,0,0); // reset the transform to the default so all other rendering is not effected
};
});
canvas {
border : 2px black solid;
}
<canvas id="gameCanvas" width=512 height=200></canvas>
Hope this was helpfull.
I'm trying to make all my enemies simultaneously shoot bullets at the player. My code works for one enemy shooting at a time, but what I'm trying to do is to make them all fire simultaneously.
For brevity's sake I'm using this simple condition to trigger the fire_bullets function : if (player.x > thisEnemy.x) { //fire bullets. What I intended to do is, the farther the player moves to the right, the more enemies start shooting bullets. Problem is the condition is only working for the first enemy in the array, while the other ones simply won't fire any bullet. You can see demo here :
https://jsfiddle.net/Lau1989/796xr7vg/
Here is my fire_bullets() function :
function fire_bullets(thisEnemy) {
var HTMLbullets = document.querySelectorAll('.HTMLbullets');
for (var b = 0; b < HTMLbullets.length; b++) {
var time = new Date().getTime()/1000 - startTime;
if (bullets[b].isOut && time > 0.5) {
if (player.x > thisEnemy.x) {
bullets[b] = bullets_pool(thisEnemy.x, thisEnemy.y);
}
startTime = new Date().getTime()/1000;
}
if (!bullets[b].isOut) {
bullets[b].y -= 4;
if (bullets[b].y <= 50) { //check if bullet is out of range and recycle it
bullets[b].isOut = true;
var thisBullet = bullets.splice(b, 1)[b];
thisBullet.x = -100;
bullets.push(thisBullet);
}
}
HTMLbullets[b].style.left = bullets[b].x +"px";
HTMLbullets[b].style.top = bullets[b].y +"px";
}
}
My latest try was to add the fire_bullets function as a property to each enemy object and then call it whenever their x position is lower than the player x position, but it only made the last enemy being triggered to fire its bullets, while the other ones stopped shooting theirs.
How should I proceed to make all my enemies simultaneously fire bullets at the player ? Is there a good performance-wise solution to do it, considering that each level frequently has dozens of enemies firing bullets at the same time ?
My newest Hobby Project is a very simple Jump'n'Run Game using JavaScript. I already wrote some code (with the help of a tutorial at lostdecadegames) and read everything about the GameLoop.
var start = true;
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1200;
canvas.height = 480;
document.body.appendChild(canvas);
var jumping = false;
var gravity = 1.5;
var pressed = true;
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "background.png";
// Hero image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
heroReady = true;
};
heroImage.src = "hero.png";
// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
monsterReady = true;
};
monsterImage.src = "monster.png";
// Game objects
var hero = {
speed_x: 50,
speed_y_up: 50,
speed_y_down: 50, // movement in pixels per second
velocity_x: 50,
velocity_y: 50
};
// Handle keyboard controls
var keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
// Update game objects
var update = function (modifier) {
if(38 in keysDown) { // Player holding up
jumping = true;
//hero.y -= hero.speed_y_up * modifier;
}
if (40 in keysDown) { // Player holding down
hero.y += hero.speed_y_down * modifier;
}
if (37 in keysDown) { // Player holding left
hero.x -= hero.speed_x * modifier;
}
if (39 in keysDown) { // Player holding right
hero.x += hero.speed_x * modifier;
}
};
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (heroReady) {
if(hero.y > 0 && hero.y < 480 && hero.x <= -32)
{
hero.x = hero.x + 1232;
ctx.drawImage(heroImage, hero.x, hero.y);
}
else if(hero.y > 0 && hero.y < 480 && hero.x >= 1200)
{
hero.x = hero.x - 1232;
ctx.drawImage(heroImage, hero.x, hero.y);
}
else if(jumping)
{
ctx.drawImage(heroImage, hero.x, hero.y-100);
jumping = false;
}
else ctx.drawImage(heroImage, hero.x, hero.y);
}
if (monsterReady) {
ctx.drawImage(monsterImage, monster.x, monster.y);
}
};
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - then;
update(delta / 500);
render();
then = now;
};
// Starting the game!
reset();
var then = Date.now();
setInterval(main, 1); // Execute as fast as possible
As you can see, I already added a fix gravity var and some speed vars. The Hero moves very smooth, so this is no problem.
I have 2 problems with the jump-Animation:
The Hero stays in the air, when the Up-Key is keep being pressed. I tried to fix this with some boolean vars, but I couldn't figure it out how to get the Hero down again.
Right now, I implemented a "dirty hack" which causes the Hero to be repainted 50px higher, but I want a smooth Jump, so that the Hero gets slower while going up and speeds up while falling. I looked up so many Tutorials and so much Example Code, but I'm too stupid to figure it out, how I get my desired Animation.
Hope you guys can give me some advice for my problem (I'm not asking for the final code, I just need some tips).
It's hard to understand exactly what the if statements inside of if (heroReady) are doing because the numbers don't mean anything to me, but it seems to me like your problem is in there.
First of all, it seems to me like jumping should the first condition checked. If one of the first conditions is true, then it doesn't matter whether or not he's jumping. I can't easily tell when each condition is true, though, so I'm going to assume that when the player is holding up,
else if(jumping)
{
ctx.drawImage(heroImage, hero.x, hero.y-100);
jumping = false;
}
gets executed like normal.
Now, assuming that, I think your issue is that jumping is determined solely by whether or not the player is holding up, because as soon as jumping is true, it becomes false. This is incorrect.
Jumping should be set to true when the player presses the up key, but it should be set to false when they remove it. It should be set to false when the animation hits the ground.
Another issue that you have is the fact that you aren't actually using the hero's attributes to render its jumping location, you're simply offsetting it. Perhaps that is just your workaround until the problem is solved, but it makes it hard to tell when the character hits the ground, because you can't start lower the character (increasing the y value) after they jump, since you never raised them by decreasing the y value.
So how do we fix this?
Here are my recommendations. You might find more elegant ways to do it by the time you're done due to refactoring, but the way you have it set up right now I think it will work fine:
Set jumping as soon as they press up, like you're doing, but only if jumping == false, because presumably your hero can't do mid-air jumps.
Immediately after you set jumping (and inside the same if statement), update their velocity.
In your update section, add another if for whether or not the player is jumping, regardless of whether or not they are pressing any keys. If they are, decrease their momentum based on gravity. Then, add a check for if their momentum is the opposite of how much you increase it when they start jumping. In other words, check if they are moving down at exactly the same rate they were moving up when they started jump. This happens at exactly the y-coordinate that they began the jump from. (This is more reliable that just checking their position, because it will work from multiple y-locations.) The alternative would be to store a variable with the y-coordinate they were at when they jumped. Either way, if their jump has ended, set jumping to false.
Since you're updating their coordinates based on jumping, in your render function, you can eliminate any jumping logic and just draw the image based on the coordinates.
Does that help at all?
Hi im totally new to javascript and need help.im making an HtML javascript game. I just wanted to ask how do i get my enemies to be clickable?? i have managed to successfully create my enemies for my game but currently they come down from the top of the game screen and exit at the bottom. If the player touches any of the enemies then it goes to game over but i want the player to be able to click on the enemies then proceed to game over instead. Ive been trying for a couple of weeks now and im lost.
Also my player currently is being controlled by the mouse, as in the mouse is the player.
Do i need to change my collison test?? im just not sure how to make the player be able to click on the enemies. do i need to register a 'click' function like onmouseclick etc?
im using:
window.addEventListener("mousedown",onDown,false);
window.addEventListener("mousemove",onMove,false);
window.addEventListener("mouseup",onUp,false);
thanks any help would be great!! just need a sbit of help to go in the right direction.
Thanks in advance :)
this is the function for when the player is moving the mouse (player). it works as my player is controlled by the mouse movememt:
function onMove(e) {
if (!e) var e = window.event;
//get mouse position
var posx = 0;
var posy = 0;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
var totalOffsetX = 0;
var totalOffsetY = 0;
var currentElement = canvas;
do{
totalOffsetX += currentElement.offsetLeft;
totalOffsetY += currentElement.offsetTop;
}
while(currentElement = currentElement.offsetParent)
mouseX = posx - totalOffsetX;
mouseY = posy - totalOffsetY;
}
}
and for mouse up:
function onUp(e) {
mouseDown = false;
}
for enemies, i have done:
enemies = new Array();
createEnemies();
and the function with the animations for the enemy objects (food and fruit items in the game) :
function createEnemies() {
var enemy
if(level>2 && Math.random()<0.2) {
var breakfastItems = Math.floor(Math.random() * breakfastsheets.length);
var tmpAnimation = new Animation(breakfastsheets[breakfastItems],4,2)
enemy = new Skull(tmpAnimation,Math.random()*(canvas.width-tmpAnimation.width),-tmpAnimation.height);
} else if(level>3 && Math.random()<0.2) {
var randomVegetable = Math.floor(Math.random() * vegetablesheets.length);
var tmpAnimation = new Animation(vegetablesheets[randomVegetable],4,2)
enemy = new Skull(tmpAnimation,Math.random()*(canvas.width-tmpAnimation.width),-tmpAnimation.height);
}else {
var randomFruit = Math.floor(Math.random() * enemysheets.length);
var tmpAnimation = new Animation(enemysheets[randomFruit],4,2)
enemy = new Skull(tmpAnimation,Math.random()*(canvas.width-tmpAnimation.width),-tmpAnimation.height);
}
enemy.setExplosionSound(explosionSoundPool);
enemies.push(enemy);
}
forgot to say that the 'Skull' thats in the enemies is this one: forget the missiles though im not using them.
function Skull (image, x,y, width, height) {
//call constructor of parent object
DisplayObject.call(this,'skull', image, x,y, width, height);
//initialise objects
this.img.play();
this.img.setLoop(true);
this.img.setRange(0,4);
//private variables
var dying = false;
var alive = true;
var speed = 5;
var explosionSound;
//public methods
this.update = function(game_area, missiles) { //game area is a Rect2d, missiles is an array of display objects.
this.y+=speed;
this.img.next();
if(!dying && missiles) {
for(var i = 0; i<missiles.length; i++) {
if(Collision.test(missiles[i],this)) {
missiles[i].kill();
dying = true;
this.img.setRange(4,8);
this.img.setLoop(false);
this.img.setFrame(0);
//play explosion sound.
if(explosionSound) explosionSound.play(0.5);
}
}
}
if(Collision.isOutside(this,game_area) || (dying && !this.img.isPlaying())) {
alive = false;
}
}
//set a sound to be played when the enemy is hit.
this.setExplosionSound = function (soundPool) {
explosionSound = soundPool;
}
this.isDying = function () {
return dying;
}
this.isDead = function () {
return !alive;
}
}
Skull.prototype = new DisplayObject();
Assuming the enemies are square objects that move around the screen,
What you can do is create a class for enemies that contain their current position with:
function newEnemy(){
this.topLeftx = 'some random value'
this.topLefty = 'some random value'
this.bottomRightx = 'some random value'
this.bottomRighty = 'some random value'
this.isSelected = false;
...
}
Then have a method that is called when the user clicks, and goes through the list of enemies one by one. For each enemy, call a 'hit test' function that will check if the user's (x,y) coordinates -on the mouse- are inside the square of the enemy.
If any of the shapes are selected, then set them to true, and on the next draw cycle, have selected enemies drawn differently or not drawn at all i.e. destroyed?
If the enemies are circular then you will need an x,y coordinate with a radius for each one. Then, simply check to see if a line drawn between the center of the circle and the mouse coordinates are less than the radius of the circle itself. Use the Pythagorean theorem to find the lengths.