Collision with 2D div's using DOM - javascript

At first: Sorry for my bad english, its hard for me to describe my problems in english :)
In school I have to program my own (simple) js game using ONLY DOM. So far so good, I already did the game control ans some other things. My problem is, to detect a collision between some images/div's. I really dont know how to do that, my teacher can't help me with that. So my problem is, to write a function which detects a collision and evt. returns true.
I hope anyoe of you can help me!
Greetings Laurin
My code:`
IT-BOY
#import url('https://fonts.googleapis.com/css?family=Press+Start+2P');
<body id="game" onload="monster1Bewegen()">
<audio autoplay loop>
<source src="jarmusik.mp3" type="audio/mpeg">
</audio>
<form name="form01">
<script type="text/javascript">
var elem = document.getElementById('game');
elem.addEventListener("keydown", KeyPressed );
</script>
<div id="main">
<h1 id="h">Dein Leben: </h1>
<progress value="100" id="p" max="100" min="0"></progress>
<div id="wiese">
<div style="width:100%;">
<img class="bg_image" id="bgimg01" width="100%" src="C:\Users\Laurin\Desktop\MEDT2\MEDT2\www\01Brein\Modul3\wiese.png">
</div>
<img name="character01" id="boy" src="ITboy.gif">
<img id="sonne" src="sonne.png">
<img id="erdblock" src="Stehdings.png">
<img id="monster1" src="monster.gif">
<img id="gewitter" src="gewitter.png">
<img id="busch" src="busch.png">
<img id="erdblock2" src="stehdings.png">
<img id="wolke" src="stehwolke.png">
<img id="monster2" src="regenbogenschwein.gif">
<img id="erdblock3" src="stehdings.png">
<img id="wolke2" src="stehwolke.png">
<img id="wolke3" src="stehwolke.png">
<img id="monster3" src="rosasaurus.gif">
</div>
</div>
</form>
<script type="text/javascript">
move("initial");
</script>
</body>
</html>`
var obj_left = 560;
var obj_top = 520;
var steps = 10;
var characterGround = obj_top + 50;
var obj_postion = "";
function move(direction) {
if(direction == "initial") {
setPos(obj_top,obj_left);
}
else {
switch(direction) {
case "up":
obj_top -= steps;
break;
case "left":
obj_left -= steps;
break;
case "right":
obj_left += steps;
break;
case "down": //Down - only if character is higher than ground
if(obj_top>characterGround) {
obj_top += steps;
}
break;
}
setPos(obj_top,obj_left);
}
}
function setPos(otop,oleft) {
document.form01.character01.style.position = "absolute";
document.form01.character01.style.zIndex = "3";
document.form01.character01.style.top = otop + "px";
document.form01.character01.style.left = oleft + "px";
}
function KeyPressed(evt) {
/**********************************************************
****** Important KeyCodes ***
***********************************************************
UP Arrow: KeyCode 38
DOWN Arrow: KeyCode 40
LEFT Arrow: KeyCode 37
RIGHT Arrow: KeyCode 39
SPACE: KeyCode 32
*********************************************************/
switch(evt.keyCode) {
//LEFT
case 37:
obj_left -= steps;
break;
//RIGHT
case 39:
obj_left += steps;
break;
//UP
case 38:
bj_top -= steps;
break;
//Down
case 40:
obj_top += steps;
break;
//Jump - Space
case 32:
jump();
break;
}
setPos(obj_top,obj_left);
}
/***********************************************************/
/* Character Jump */
/***********************************************************/
var yVel = 0; //Velocity in the Y Direction (top)
var gravity = 2; //Gravity
var isJumping = false; //Saves the state if the character is jumping or not - prevent multiple jumps
var drop;
function jump() { //If the character isn't already jumping - jump
if (isJumping == false) {
yVel = -150;
obj_top += yVel;
setPos(obj_top,obj_left);
isJumping = true;
droploop();
}
}
function droploop() {
//if isJumping is true
if(isJumping) {
obj_top += gravity;
setPos(obj_top,obj_left);
//Check if the character has reached the ground the drop is stopped
if (obj_top > characterGround) {
obj_top = characterGround;
setPos(obj_top,obj_left);
yVel = 0;
isJumping = false;
clearInterval(drop);
}
else {
//if the character has not reached the ground the loop for the drop is started
drop = setInterval(droploop, 500);
}
}
}
/***********************************************************/
/* Set Szene */
/***********************************************************/
var x = 830;
var left = false;
function monster1Bewegen() {
if(x>=810 && x<=900){
if(left)
x--;
else
x++;
}
if(x == 810 || x == 900) {
left = !left;
}
document.getElementById('monster1').style.left = x + "px";
window.setTimeout(monster1Bewegen, 30);
}

Try this here is demo https://jsfiddle.net/ryanoc/TG2M7/
function getPositions(box) {
var $box = $(box);
var pos = $box.position();
var width = $box.width();
var height = $box.height();
return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ]
];
}
function comparePositions(p1, p2) {
var x1 = p1[0] < p2[0] ? p1 : p2;
var x2 = p1[0] < p2[0] ? p2 : p1;
return x1[1] > x2[0] || x1[0] === x2[0] ? true : false;
}
function checkCollisions(){
var box = $(".bomb")[0];
var pos = getPositions(box);
var pos2 = getPositions(this);
var horizontalMatch = comparePositions(pos[0], pos2[0]);
var verticalMatch = comparePositions(pos[1], pos2[1]);
var match = horizontalMatch && verticalMatch;
if (match) { $("body").append("<p>COLLISION !!!</p>"); }
}

Related

how can disable navigation button after reached on the last slide in javascript

the function is as under, want to stop or disable up arrow when slider is at last record and disable down arrow when slider is at first record.
upArrow.onclick = function(){
if(x > "-900"){
x = x - 300;
slide.style.top = x + "px";
}
downArrow.onclick = function(){
if(x < 0){
x = x + 300;
slide.style.top = x + "px";
}
}
You can disable the arrow by changing its pointer events and color when it reaches the desired value, for example:
upArrow.onclick = function(){
if(x < 0){
x = x + 300;
slide.style.top = x + "px";
downArrow.style.pointerEvents = "";
downArrow.style.backgroundColor = "";
if (x == 0) {
upArrow.style.pointerEvents = "none";
upArrow.style.backgroundColor = "grey";
}
}
}
downArrow.onclick = function(){
if(x > -900){
x = x - 300;
slide.style.top = x + "px";
upArrow.style.pointerEvents = "";
upArrow.style.backgroundColor = "";
if (x == -900) {
downArrow.style.pointerEvents = "none";
downArrow.style.backgroundColor = "grey";
}
}
}
Note: I did a little rewrite to the code to what I see more meaningful.

Making game character walk, Javascript

I'm trying to make a simple game with a walking character. When a button is pressed down i want to continuously switch between two images (while the button is held down) which will make it look like the character is moving. It does move, however the switch between pictures happens only once at the beginning. Can anyone tell me what am i doing wrong? Or suggest a way to do it. Been stuck on this for hours.
Any help will be much appreciated.
<!DOCTYPE html>
<html>
<head>
<link href="./styles/style.css" rel="stylesheet" type="text/css"><link>
<meta charset="utf-8" />
<title>Playa Haters</title>
<style>
* { padding: 0; margin: 0; }
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="450"></canvas>
<img id="step1" src="media/step1.jpg" width="120" height="150">
<img id="step2" src="media/step2.jpg" width="120" height="150">
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d"); //get content
var step1 = document.getElementById("step1");
var step2 = document.getElementById("step2");
var currentStep = step1;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
var rightPressed = false;
var leftPressed = false;
var step = 5;
var distance = null;
function keyDownHandler(e) {
if(e.keyCode == 39){
rightPressed = true;
}
else if(e.keyCode = 37){
leftPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
//initial position
var x = canvas.width/2;
var y = canvas.height/2 - 100;
function drawShooter(){
ctx.drawImage(currentStep, x, y);
}
function walk(){
if (currentStep = step1){
currentStep = step2;
}
else if (currentStep = step2){
currentStep = step1;
}
}
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawShooter();
if(rightPressed) {
x += step;
setInterval(walk, 500);
}
else if(leftPressed) {
x -= step;
setInterval(walk, 500);
}
}
setInterval(draw, 20);
</script>
</body>
</html>
On your walk function you are assigning instead of comparing inside the if statement... you have:
function walk(){
if (currentStep = step1){
currentStep = step2;
}
else if (currentStep = step2){
currentStep = step1;
}
}
You should have instead:
function walk(){
if (currentStep === step1){
currentStep = step2;
}
else if (currentStep === step2){
currentStep = step1;
}
}
Note the triple equals inside the conditional. This should solve the problem with swapping the images.

How can I create the detection for this javascript program of mine?

I've been building on top of an assignment we did in class and I'm stumped at the detection part.
I want my Mew to be "caught" when he stands on top of the pokeball, the player moves the keyboard to control the Mew and the pokeball randomly repositions on a time delay.
How can I create a function that will detect when the mew.gif is in overlap with the pokeball?
var _stage = document.getElementById("stage");
var _Mew = document.querySelector("img");
var _PokeBall = document.getElementById("PokeBall");
_stage.style.width = "800px";
_stage.style.height = "600px";
_stage.style.backgroundColor = "black";
_stage.style.marginLeft = "auto";
_stage.style.marginRight = "auto";
_Mew.style.position = "relative"; // Uses top and left from parent
_PokeBall.style.position = "relative"; // Uses top and left from parent
var leftPressed = false;
var rightPressed = false;
var upPressed = false;
var downPressed = false;
var player = [ 400, 300 ]; // Left, Top
var PokeBall = [100, 100];// Top, Left
var uIval = setInterval(update, 22.22); // 30fps update loop
var map = []; // empty Map Array
window.addEventListener("keydown", onKeyDown);
window.addEventListener("keyup", onKeyUp);
var Pval= setInterval(MovePokeball, 2000);
function generateMap()
{
for (var row = 0; row < 2; row++)
{
for(var col = 0; col <8; col++)
{
console.log("In row "+row);
}
}
}
/*map[row] = []; // Creating new array in specified row
for (var col = 0; col <8; col++)
{
console.log("In row "+row+"doing col"+col);
}
*/
function onKeyDown(event)
{
switch(event.keyCode)
{
case 37: // Left.
if ( leftPressed == false )
leftPressed = true;
break;
case 39: // Right.
if ( rightPressed == false )
rightPressed = true;
break;
case 38: // Up.
if ( upPressed == false )
upPressed = true;
break;
case 40: // Down.
if ( downPressed == false )
downPressed = true;
break;
default:
console.log("Unhandled key.");
break;
}
}
function onKeyUp(event)
{
switch(event.keyCode)
{
case 37: // Left.
leftPressed = false;
break;
case 39: // Right.
rightPressed = false;
break;
case 38: // Up.
upPressed = false;
break;
case 40: // Down.
downPressed = false;
break;
default:
console.log("Unhandled key.");
break;
}
}
function update() // Going to run 30fps
{
movePlayer();
// move enemies
// collision check
// animate sprites
PlayerCaught();
render();
}
function movePlayer()
{
if ( leftPressed == true && player[0] >= _Mew.width/2)
player[0] -= 10;
if ( rightPressed == true && player[0] < 800 - _Mew.width/2)
player[0] += 10;
if ( upPressed == true && player[1] >= _Mew.height/2 )
player[1] -= 10;
if ( downPressed == true && player[1] < 600 - _Mew.width/2)
player[1] += 10;
}
function render()
{
_Mew.style.left = player[0]-_Mew.width/2+"px";
_Mew.style.top = player[1]-_Mew.width/2+"px";
}
function PlayerCaught()
{
if (_PokeBall [100,100] = player [100,100])
window.alert("Mew Has Been Captured!")
}
function MovePokeball()
{
_PokeBall.style.left= Math.floor(Math.random()*801)+"px";
_PokeBall.style.top= Math.floor(Math.random()*601)+"px";
}
You're asking about collision detection. This is done by determining if two polygons intersect. Since your program is very simplified, I'm offering a very simplified solution. We're going to determine if the graphics intersect. This is not the ideal way to do it. Normally, graphics and physics are completely separated. But this will work (mostly), and hopefully it'll encourage you to continue to experiment.
First, we need the height and width of both images so we can do our geometric magic. This can be easily set in JavaScript, just like you did for _stage. However, you've already defined the src of your images elsewhere (probably in HTML), so it would be best to define the height and width there.
HTML Example:
<img id="PokeBall" src="pokeball.png" style="width:50px; height:50px" />
Note: This uses "inline CSS" which is another bad practice. But this works, and I don't want to overcomplicate simple things right now.
Now your PlayerCaught method has all the information it needs to do it's job, so how do we detect collisions? If we're working with rectangles, it's very simple. We just determine if any of the corners of one object are inside the other object. So how do we do that? Basically, we see if they intersect on both the X and Y axes.
Take two rectangles: A and B. Both have four edges: top, left, right, and bottom. The edges top and bottom are Y values, and the edges left and right are X values. The two rectangles intersect if any of the following is true:
(
A.left < B.left < A.right
OR A.left < B.right < A.right
) AND (
A.top < B.top < A.bottom
OR A.top < B.bottom < A.bottom
)
Translate that into JavaScript and you've got your collision detection function. To get the edges in your program, use the following:
function findEdges(img){
var result = [];
result["left"] = parseInt(img.style.left, 10);
result["top"] = parseInt(img.style.top, 10);
result["right"] = result["left"] + parseInt(img.style.width, 10);
result["bottom"] = result["top"] + parseInt(img.style.height, 10);
return result;
}
You can see that we are using the inline style that we set earlier for the width and height as well as the top and left you are already using for rendering.
SPOILER...
Putting all the pieces together might look like:
function PlayerCaught(){
if (detectImgCollision(_PokeBall, _Mew)){
window.alert("Mew Has Been Captured!")
}
}
function detectImgCollision(imgA, imgB){
var A = findEdges(imgA);
var B = findEdges(imgB);
return detectRectCollision(A, B);
}
function detectRectCollision(A, B){
return (
isBetween(A.left, B.left, A.right)
|| isBetween(A.left, B.right, A.right)
) && (
isBetween(A.top, B.top, A.bottom)
|| isBetween(A.top, B.bottom, A.bottom)
);
}
function isBetween(low, middle, high){
return (low <= middle && middle <= high);
}

Snake Game with Mobile Button Controls

In this Snake game, I need the buttons to control the snake just like the arrow keys do. This will allow the game to be played on a mobile device. You can see i have code in there for the buttons, but they are not working properly and not controlling the movement of the snake.
Any advice to make the buttons work would be greatly appreciated! thanks!
HTML
<section class="game" id="share">
<div class="container">
<div class="columns twelve borders center">
<div class="game-container">
<div class="container">
<div class="SplashScreen">
<h1>
Snake
</h1>
<h2>
Click To Start.
</h2>
<input class="StartButton" type="button" value="Start" />
</div>
<div class="FinishScreen" style="display:none">
<h1>
Game Over
</h1>
<p>
Your score was: <span id="score"></span>
</p>
<input class="StartButton" type="button" value="Restart" />
</div>
<canvas id="canvasArea" height="300" width="300" style="display:none;"></canvas>
</div>
<div class="button-pad">
<div class="btn-up">
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-up.png" alt="Up" class="button up-btn" />
</div>
<div class="btn-right">
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-right.png" alt="Right" class="button right-btn" />
</div>
<div class="btn-down">
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-down.png" alt="Down" class="button down-btn" />
</div>
<div class="btn-left">
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-left.png" alt="Left" class="button left-btn" />
</div>
</div>
</div>
</div>
</div>
</section>
JAVASCRIPT
( function( $ ) {
$( function() {
$(document).ready(function () {
$(".StartButton").click(function () {
$(".SplashScreen").hide();
$(".FinishScreen").hide();
$("#canvasArea").show();
init();
});
//Canvas stuff
var canvas = $("#canvasArea")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvasArea").width();
var h = $("#canvasArea").height();
//Lets save the cell width in a variable for easy control
var sw = 10;
var direction;
var nd;
var food;
var score;
//Lets create the snake now
var snake_array; //an array of cells to make up the snake
function endGame() {
$("#canvasArea").hide();
$("#score").text(score);
$(".FinishScreen").show();
}
function init() {
direction = "right"; //default direction
nd = [];
create_snake();
create_food(); //Now we can see the food particle
//finally lets display the score
score = 0;
//Lets move the snake now using a timer which will trigger the paint function
//every 60ms
if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 60);
}
function create_snake() {
var length = 5; //Length of the snake
snake_array = []; //Empty array to start with
for (var i = length - 1; i >= 0; i--) {
//This will create a horizontal snake starting from the top left
snake_array.push({
x: i,
y: 0
});
}
}
//Lets create the food now
function create_food() {
food = {
x: Math.round(Math.random() * (w - sw) / sw),
y: Math.round(Math.random() * (h - sw) / sw),
};
//This will create a cell with x/y between 0-44
//Because there are 45(450/10) positions accross the rows and columns
}
//Lets paint the snake now
function paint() {
if (nd.length) {
direction = nd.shift();
}
//To avoid the snake trail we need to paint the BG on every frame
//Lets paint the canvas now
ctx.fillStyle = "#0056a0";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "#ffffff";
ctx.strokeRect(0, 0, w, h);
//The movement code for the snake to come here.
//The logic is simple
//Pop out the tail cell and place it infront of the head cell
var nx = snake_array[0].x;
var ny = snake_array[0].y;
//These were the position of the head cell.
//We will increment it to get the new head position
//Lets add proper direction based movement now
if (direction == "right") nx++;
else if (direction == "left") nx--;
else if (direction == "up") ny--;
else if (direction == "down") ny++;
//Lets add the game over clauses now
//This will restart the game if the snake hits the wall
//Lets add the code for body collision
//Now if the head of the snake bumps into its body, the game will restart
if (nx == -1 || nx == w / sw || ny == -1 || ny == h / sw || check_collision(nx, ny, snake_array)) {
//end game
return endGame();
}
//Lets write the code to make the snake eat the food
//The logic is simple
//If the new head position matches with that of the food,
//Create a new head instead of moving the tail
if (nx == food.x && ny == food.y) {
var tail = {
x: nx,
y: ny
};
score++;
//Create new food
create_food();
} else
{
var tail = snake_array.pop(); //pops out the last cell
tail.x = nx;
tail.y = ny;
}
//The snake can now eat the food.
snake_array.unshift(tail); //puts back the tail as the first cell
for (var i = 0; i < snake_array.length; i++) {
var c = snake_array[i];
//Lets paint 10px wide cells
paint_cell(c.x, c.y);
}
//Lets paint the food
paint_cell(food.x, food.y);
//Lets paint the score
var score_text = "Score: " + score;
ctx.fillStyle = "#ffffff";
ctx.fillText(score_text, 5, h - 5);
//Set the font and font size
ctx.font = '12px Arial';
//position of the fill text counter
ctx.fillText(itemCounter, 10, 10);
}
//Lets first create a generic function to paint cells
function paint_cell(x, y) {
ctx.fillStyle = "#d8d8d8";
ctx.fillRect(x * sw, y * sw, sw, sw);
}
function check_collision(x, y, array) {
//This function will check if the provided x/y coordinates exist
//in an array of cells or not
for (var i = 0; i < array.length; i++) {
if (array[i].x == x && array[i].y == y) return true;
}
return false;
}
// Lets prevent the default browser action with arrow key usage
var keys = {};
window.addEventListener("keydown",
function(e){
keys[e.keyCode] = true;
switch(e.keyCode){
case 37: case 39: case 38: case 40: // Arrow keys
case 32: e.preventDefault(); break; // Space
default: break; // do not block other keys
}
},
false);
window.addEventListener('keyup',
function(e){
keys[e.keyCode] = false;
},
false);
//Lets add the keyboard controls now
$(document).keydown(function (e) {
var key = e.which;
var td;
if (nd.length) {
var td = nd[nd.length - 1];
} else {
td = direction;
}
//We will add another clause to prevent reverse gear
if (key == "37" && td != "right") nd.push("left");
else if (key == "38" && td != "down") nd.push("up");
else if (key == "39" && td != "left") nd.push("right");
else if (key == "40" && td != "up") nd.push("down");
//The snake is now keyboard controllable
});
});
$(document).on('click', '.button-pad > button', function(e) {
if ($(this).hasClass('left-btn')) {
e = 37;
}
else if ($(this).hasClass('up-btn')) {
e = 38;
}
else if ($(this).hasClass('right-btn')) {
e = 39;
}
else if ($(this).hasClass('down-btn')) {
e = 40;
}
$.Event("keydown", {keyCode: e});
});
});
})( jQuery );
FIDDLE
AND TIME
So basically you have some errors going on. Your first one is your styling. You really need to make your styles more flexible, but this will solve the right button problem I was having.
.button-pad > div {
z-index: 9999;
width: 50px;
}
http://jsfiddle.net/34oeacnm/8/
$(document).on('click', '.button-pad .button', function(e) {
var e = jQuery.Event("keydown");
if ($(this).hasClass('left-btn')) {
e.which = 37;
}
else if ($(this).hasClass('up-btn')) {
e.which = 38;
}
else if ($(this).hasClass('right-btn')) {
e.which = 39;
}
else if ($(this).hasClass('down-btn')) {
e.which = 40;
}
$(document).trigger(e);
});
You had some of your selectors off. And I stole some information on how to trigger from Definitive way to trigger keypress events with jQuery.
Here is the code to add moile control to the snake game; (If you want the whole code for the snake game please comment);
//Here is javascript;
// left key
function l() {
if(snake.dx === 0) {
snake.dx = -grid;
snake.dy = 0;
}
}
// up key
function u() {
if(snake.dy === 0) {
snake.dy = -grid;
snake.dx = 0;
}
}
// right key
function r() {
if(snake.dx === 0) {
snake.dx = grid;
snake.dy = 0;
}
}
// down key
function d() {
if(snake.dy === 0) {
snake.dy = grid;
snake.dx = 0;
}
}
Here is HTML;
<div>
<button onclick="u()" type="button" id="U">U</button>
<button onclick="l()" type="button" id="L">L</button>
<button onclick="r()" type="button" id="R">R</button>
<button onclick="d()" type="button" id="D">D</button>
</div>
Description: I simply added four buttons in the html page, created four functions in the js which will move snake as it should move in different directions and simply added them to the 'onclick' attribute of the different buttons respectively.

CraftyJS: I can't destroy an entity with .onHit

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?
One problem: when you try to destroy the alien, the alien variable isn't actually in scope. (You've declared it in a different function.) So there's no way alien.destroy(); will work.
Second problem: the function you pass to .onHit("alien", callback) will only be run when the laser hits an entity with the "alien" component. It has no idea what variable name you assigned the entity. However, the callback function will be passed information about what entities it's colliding with, and you can use that to resolve the collision.

Categories

Resources