I am having a problem with craftyJS. I made a ship that shoots lasers, but I want the lasers to destroy an entity when it collides with it. I already tried to do this, but it don't work. Here is my code:
Crafty.init(1340,650, document.getElementById('game'));
Crafty.defineScene("gameStart", function() {
function newAlien(){
var random = Math.floor(Math.random() * 4) + 1;
switch(random){
case 1:
var alien = Crafty.e("2D, DOM, Image, Collision")
.image("alien1.png");
alien.x = ship.x;
alien.y = 20
break;
case 2:
var alien = Crafty.e("2D, DOM, Image, Collision")
.image("alien2.png");
alien.x = ship.x;
alien.y = 20;
break;
case 3:
var alien = Crafty.e("2D, DOM, Image, Collision")
.image("alien3.png");
alien.x = ship.x;
alien.y = 20;
break;
case 4:
var alien = Crafty.e("2D, DOM, Image, Collision")
.image("alien4.png");
alien.x = ship.x;
alien.y = 20;
break;
}
}
function newLaser(){
var laser = Crafty.e("2D, DOM, Image, Collision")
.image("laser.png")
.collision()
.onHit("alien", function(){
laser.destroy();
alien.destroy();
});
laser.y = 510;
laser.x = ship.x + 40;
var moveLaser = setInterval(function(){
if(laser.y < 1){
clearInterval(moveLaser);
laser.destroy();
} else {
laser.y = laser.y - 4;
}
}, 1);
}
function checkBorder(){
if(ship.x < 0 || ship.x > 1250){
Crafty.enterScene("gameStart");
}
}
function goLeft(){
var goLeftCount = 65;
var goLeftInterval = setInterval(function(){
if(goLeftCount === 0){
clearInterval(goLeftInterval);
checkBorder();
} else {
ship.x = ship.x - 1;
goLeftCount -= 1;
}
}, 1);
}
function goRight(){
var goRightCount = 65;
var goRightInterval = setInterval(function(){
if(goRightCount === 0){
clearInterval(goRightInterval);
checkBorder();
} else {
ship.x = ship.x + 1;
goRightCount -= 1;
}
}, 1);
}
var ship = Crafty.e("2D, DOM, Image, Bind")
.image("ship.png")
.bind('KeyDown', function(e) {
if(e.key == Crafty.keys['LEFT_ARROW']) {
goLeft();
} else if (e.key == Crafty.keys['RIGHT_ARROW']) {
goRight();
} else if(e.key == Crafty.keys['SPACE']) {
newLaser();
}
});
ship.y = 520;
ship.x = 600;
newAlien();
});
Crafty.enterScene("gameStart");
Can anyone please tell me what are the problems with my code?