Arrow Keys in Car Game - javascript

let score = document.querySelector('.score');
let startScreen = document.querySelector('.startScreen');
let gameArea = document.querySelector('.gameArea');
let startGame = document.querySelector('#startGame');
let keys = {
ArrowUp: false,
ArrowLeft: false,
ArrowRight: false,
ArrowDown: false
}
let player = {
speed: 5
};
startGame.addEventListener('click', start)
console.log(gameArea);
document.addEventListener('keydown', keyDown);
document.addEventListener('keyup', keyUp);
function keyDown(e) {
keys[e.key] = true;
e.preventDefault();
//console.log(e.key);
//
console.log(keys);
}
function keyUp(e) {
e.preventDefault();
keys[e.key] = false;
console.log(e.key);
console.log(keys);
}
function gamePlay() {
// console.log('now play the game');
let keys = {
ArrowUp: false,
ArrowLeft: false,
ArrowRight: false,
ArrowDown: false
}
if (keys.ArrowUp) {
player.y -= 5;
}
if (keys.ArrowDown) {
player.y += 5;
}
if (keys.ArrowLeft) {
player.x -= 5;
}
if (keys.ArrowRight) {
player.x += 5;
}
car.style.top = player.y + "px";
car.style.left = player.x + "px";
window.requestAnimationFrame(gamePlay)
}
function start() {
let car = document.createElement('div');
car.setAttribute('class', 'car')
gameArea.appendChild(car);
gameArea.classList.remove('hide');
startScreen.classList.add('hide');
player.start = true;
player.y = car.offsetTop;
player.x = car.offsetLeft;
console.log(car.offsetTop);
car.style.top = player.y + "px";
car.style.left = player.x + "px";
console.log(car)
}
let car = document.querySelector('.car');
.car {
width: 50px;
height: 70px;
background: red;
position: absolute;
left: 50px;
top: 120px;
}
.hide {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Car Game</title>
</head>
<body>
<div class="carGame">
<div class="score">
</div>
<div class="startScreen">
<p>
Arrow keys to move <br> If you hit another car you will lose.
<button id="startGame">Start Game</button>
</p>
</div>
<div class="gameArea hide"></div>
</div>
</body>
</html>
I am creating a javascript car Game but I am trying to move my car by arrow keys but it is not moving.
Please 🙏 Tell me what is mistake in my code and I want that when I press arrow keys it moves left right up down please check the mistake in my code

The current code makes no attempt to move the .car element when a key is pressed. All it does is sets an object property to true:
keys[e.key] = true;
I would suggest creating another function, moveCar(), that can be called from the keyDown event listener. This function will hold the positioning logic that is currently found in gamePlay().
Also, when you crate the car element, assign it to a variable that is accessible to the whole application.
let score = document.querySelector(".score");
let startScreen = document.querySelector(".startScreen");
let gameArea = document.querySelector(".gameArea");
let startGame = document.querySelector("#startGame");
let car; /* This will reference the `car` element once created */
let keys = {
ArrowUp: false,
ArrowLeft: false,
ArrowRight: false,
ArrowDown: false
};
let player = {
speed: 5
};
startGame.addEventListener("click", start);
console.log(gameArea);
document.addEventListener("keydown", keyDown);
document.addEventListener("keyup", keyUp);
function keyDown(e) {
keys[e.key] = true;
e.preventDefault();
//console.log(e.key);
//
console.log(keys);
moveCar();
}
function keyUp(e) {
e.preventDefault();
keys[e.key] = false;
console.log(e.key);
console.log(keys);
}
function gamePlay() {
// console.log('now play the game');
let keys = {
ArrowUp: false,
ArrowLeft: false,
ArrowRight: false,
ArrowDown: false
};
window.requestAnimationFrame(gamePlay);
}
function start() {
car = document.createElement("div");
car.setAttribute("class", "car");
gameArea.appendChild(car);
gameArea.classList.remove("hide");
startScreen.classList.add("hide");
player.start = true;
player.y = car.offsetTop;
player.x = car.offsetLeft;
console.log(car.offsetTop);
car.style.top = player.y + "px";
car.style.left = player.x + "px";
console.log(car);
}
function moveCar() {
if (keys.ArrowUp) {
player.y -= 5;
}
if (keys.ArrowDown) {
player.y += 5;
}
if (keys.ArrowLeft) {
player.x -= 5;
}
if (keys.ArrowRight) {
player.x += 5;
}
car.style.top = player.y + "px";
car.style.left = player.x + "px";
}
.car {
width: 50px;
height: 70px;
background: red;
position: absolute;
left: 50px;
top: 120px;
}
.hide {
display: none;
}
<div class="carGame">
<div class="score">
</div>
<div class="startScreen">
<p>
Arrow keys to move <br> If you hit another car you will lose.
<button id="startGame">Start Game</button>
</p>
</div>
<div class="gameArea hide"></div>
</div>

Related

How to stop an element in JavaScript at the screen border?

I am beginner in JavaScript and I'm trying to create a simple game. I'm looking for a way to stop the rectangle when it touches the screen border by stopping setInterval(), I can't get the value of the left screen border.
const element = document.querySelector('#rectangle');
let a = 1;
document.addEventListener('keydown', function (e) {
switch (e.keyCode) {
case 37:
let leftInterval = setInterval(moveLeft, 100);
break;
case 39:
let rightInterval = setInterval(moveRight, 100);
break;
}
});
window.addEventListener('load', () => {
rectangle.style.position = 'absolute';
rectangle.style.left = "44%";
});
let moveLeft = () => {
element.style.left = parseInt(element.style.left) - a + '%';
}
let moveRight = () => {
element.style.left = parseInt(element.style.left) + a + '%';
}
function clearinterval() {
if (element.style.left < 0)
clearinterval(leftInterval);
}
clearinterval();
body {
background-color: brown;
box-sizing: border-box;
width: 100%;
height: 100%;
}
#rectangle {
bottom: 2.5%;
background-color: burlywood;
width: 12%;
height: 14px;
}
<div id="rectangle"></div>
This will help you.
const element = document.querySelector('#rectangle');
let a = 1;
document.addEventListener('keydown', function (e) {
switch (e.keyCode) {
case 37:
let leftInterval = setInterval(moveLeft, 100);
break;
case 39:
let rightInterval = setInterval(moveRight, 100);
break;
}
});
window.addEventListener('load', () => {
rectangle.style.position = 'absolute';
rectangle.style.left = "44%";
});
let moveLeft = () => {
if (parseInt(window.getComputedStyle(element,null).getPropertyValue("left")) > 10) {
element.style.left = parseInt(element.style.left) - a + '%';
}
}
let moveRight = () => {
if (parseInt(window.getComputedStyle(element,null).getPropertyValue("right")) > 10) {
element.style.left = parseInt(element.style.left) + a + '%';
}
}
// function clearinterval() {
// // clearinterval(leftinterval);
// }
// clearinterval();

How to add a game menu

I am trying to add a generic game menu with "start" to initiate the game. How do I go about doing this? Here is the code:
var LEFT_KEY = 37;
var UP_KEY = 38;
var RIGHT_KEY = 39;
var DOWN_KEY = 40;
var SPACE_KEY = 32;
var HERO_MOVEMENT = 3;
var lastLoopRun = 0;
var score = 0;
var iterations = 0;
var controller = new Object();
var enemies = new Array();
function createSprite(element, x, y, w, h) {
var result = new Object();
result.element = element;
result.x = x;
result.y = y;
result.w = w;
result.h = h;
return result;
}
function toggleKey(keyCode, isPressed) {
if (keyCode == LEFT_KEY) {
controller.left = isPressed;
}
if (keyCode == RIGHT_KEY) {
controller.right = isPressed;
}
if (keyCode == UP_KEY) {
controller.up = isPressed;
}
if (keyCode == DOWN_KEY) {
controller.down = isPressed;
}
if (keyCode == SPACE_KEY) {
controller.space = isPressed;
}
}
function intersects(a, b) {
return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
}
function ensureBounds(sprite, ignoreY) {
if (sprite.x < 20) {
sprite.x = 20;
}
if (!ignoreY && sprite.y < 20) {
sprite.y = 20;
}
if (sprite.x + sprite.w > 480) {
sprite.x = 480 - sprite.w;
}
if (!ignoreY && sprite.y + sprite.h > 480) {
sprite.y = 480 - sprite.h;
}
}
function setPosition(sprite) {
var e = document.getElementById(sprite.element);
e.style.left = sprite.x + 'px';
e.style.top = sprite.y + 'px';
}
function handleControls() {
if (controller.up) {
hero.y -= HERO_MOVEMENT;
}
if (controller.down) {
hero.y += HERO_MOVEMENT;
}
if (controller.left) {
hero.x -= HERO_MOVEMENT;
}
if (controller.right) {
hero.x += HERO_MOVEMENT;
}
if (controller.space) {
var laser = getFireableLaser();
if (laser) {
laser.x = hero.x + 9;
laser.y = hero.y - laser.h;
}
}
ensureBounds(hero);
}
function getFireableLaser() {
var result = null;
for (var i = 0; i < lasers.length; i++) {
if (lasers[i].y <= -120) {
result = lasers[i];
}
}
return result;
}
function getIntersectingLaser(enemy) {
var result = null;
for (var i = 0; i < lasers.length; i++) {
if (intersects(lasers[i], enemy)) {
result = lasers[i];
break;
}
}
return result;
}
function checkCollisions() {
for (var i = 0; i < enemies.length; i++) {
var laser = getIntersectingLaser(enemies[i]);
if (laser) {
var element = document.getElementById(enemies[i].element);
element.style.visibility = 'hidden';
element.parentNode.removeChild(element);
enemies.splice(i, 1);
i--;
laser.y = -laser.h;
score += 100;
} else if (intersects(hero, enemies[i])) {
gameOver();
} else if (enemies[i].y + enemies[i].h >= 500) {
var element = document.getElementById(enemies[i].element);
element.style.visibility = 'hidden';
element.parentNode.removeChild(element);
enemies.splice(i, 1);
i--;
}
}
}
function gameOver() {
var element = document.getElementById(hero.element);
element.style.visibility = 'hidden';
element = document.getElementById('gameover');
element.style.visibility = 'visible';
}
function showSprites() {
setPosition(hero);
for (var i = 0; i < lasers.length; i++) {
setPosition(lasers[i]);
}
for (var i = 0; i < enemies.length; i++) {
setPosition(enemies[i]);
}
var scoreElement = document.getElementById('score');
scoreElement.innerHTML = 'SCORE: ' + score;
}
function updatePositions() {
for (var i = 0; i < enemies.length; i++) {
enemies[i].y += 4;
enemies[i].x += getRandom(7) - 3;
ensureBounds(enemies[i], true);
}
for (var i = 0; i < lasers.length; i++) {
lasers[i].y -= 12;
}
}
function addEnemy() {
var interval = 50;
if (iterations > 1500) {
interval = 5;
} else if (iterations > 1000) {
interval = 20;
} else if (iterations > 500) {
interval = 35;
}
if (getRandom(interval) == 0) {
var elementName = 'enemy' + getRandom(10000000);
var enemy = createSprite(elementName, getRandom(450), -40, 35, 35);
var element = document.createElement('div');
element.id = enemy.element;
element.className = 'enemy';
document.children[0].appendChild(element);
enemies[enemies.length] = enemy;
}
}
function getRandom(maxSize) {
return parseInt(Math.random() * maxSize);
}
function loop() {
if (new Date().getTime() - lastLoopRun > 40) {
updatePositions();
handleControls();
checkCollisions();
addEnemy();
showSprites();
lastLoopRun = new Date().getTime();
iterations++;
}
setTimeout('loop();', 2);
}
document.onkeydown = function(evt) {
toggleKey(evt.keyCode, true);
};
document.onkeyup = function(evt) {
toggleKey(evt.keyCode, false);
};
var hero = createSprite('hero', 250, 460, 20, 20);
var lasers = new Array();
for (var i = 0; i < 3; i++) {
lasers[i] = createSprite('laser' + i, 0, -120, 2, 50);
}
loop();
#hero {
/* background: #ff0000; */
background-image: url("man-of-space.png");
width: 40px;
height: 40px;
position: absolute;
}
#background {
background-image: url("space.png");
/* background: #000000; */
width: 500px;
height: 500px;
position: absolute;
left: 0px;
top: 0px;
}
.laser {
background: #00ff00;
width: 2px;
height: 50px;
position: absolute;
}
.enemy {
background-image: url("spaceship.png");
background-size: 40px 40px;
width: 40px;
height: 40px;
position: absolute;
}
#score {
color: #ffffff;
font-size: 18pt;
position: absolute;
left: 20px;
top: 20px;
}
#gameover {
color: #ff0000;
font-size: 20px;
position: absolute;
left: 160px;
top: 200px;
visibility: hidden;
}
<div id="background"></div>
<div id="hero"></div>
<div class="laser" id="laser0"></div>
<div class="laser" id="laser1"></div>
<div class="laser" id="laser2"></div>
<div id="score"></div>
<div id="gameover">GAME OVER</div>
You could wrap your game UI in a <div id="game" style="display: none;"> element so it will be hidden when the page is loaded. Then wrap your start menu in a <div id="startMenu"> element with a <button id="startButton">Start</button> that will be used to hide the start menu and show the game UI.
In your JS code you could wrap your game in a function so it can be started when you call it.
HTML:
<div id="startMenu">
<button id="startButton">Start</button>
</div>
<div id="game" style="display: none;">
<div id="background"></div>
<div id="hero"></div>
<div class="laser" id="laser0"></div>
<div class="laser" id="laser1"></div>
<div class="laser" id="laser2"></div>
<div id="score"></div>
<div id="gameover">GAME OVER</div>
</div>
JS:
function startGame() {
var LEFT_KEY = 37;
var UP_KEY = 38;
var RIGHT_KEY = 39;
var DOWN_KEY = 40;
var SPACE_KEY = 32;
var HERO_MOVEMENT = 3;
[...Your game code...]
loop();
}
document.getElementById('startButton').onclick = function() {
document.getElementById('startMenu').style.display = "none";
document.getElementById('game').style.display = "";
startGame();
};
Now you have a start menu (<div id="startMenu">) that you can customize however you like, and a game UI (<div id="game">) that will be shown only after the start button is pressed.
Add more HTML would be my suggestion. Maybe make a div that has all the start screen elements you need in it. When the start function happens, set that div's innerHTML to "".
Example:
document.getElementById('yourDivIdHere').innerHTML = '';

div element onkeypress isn't working properly

I'm attempting to create a classic "Snake game" using only vanilla Javascript. I got an issue with the snake movements when arrow keys are pressed. It didn't work as supposed to.
The entire code is look like this.
HTML
<div class="canvas" id="canvas">
<div class="snake" id="snake"></div>
<div class="food-item" id="food-item"></div>
</div>
CSS
.canvas {
position: relative;
width: 500px;
height: 500px;
background-color: rgba(203, 200, 200, 0.51);
}
.snake {
width: 18px;
height: 18px;
transform: translate(215px, 246px);
background-color: rgba(180, 9, 180, 0.808);
border-radius: 25px;
}
JS
//the position of element before movement
var pos = 0;
let ele = document.getElementById("snake");
//Add an event for button press
window.addEventListener("keydown", (key) => {
var keycode = key.key;
return {
keycode: keycode,
start: start(keycode),
};
});
//movement of the element
function start(key) {
let keys = key;
function automove() {
try {
if (pos === 380) {
clearInterval(movement);
} else if (keys === "ArrowRight") {
pos++;
ele.style.transform = "translate(" + pos + "px)";
} else if (keys === "ArrowLeft") {
pos++;
ele.style.transform = "translate(" + -pos + "px)";
} else if (keys === "ArrowUp") {
pos++;
ele.style.transform = "translateY(" + pos + "px)";
} else if (keys === "ArrowDown") {
pos++;
ele.style.transform = "translateY(" + -pos + "px)";
} else {
console.log("invalid command: " + Error);
}
} catch (error) {
console.log("Error: " + error);
}
}
const movement = setInterval(automove, 1000);
return movement;
}
the behavior of the code is this
What I'm doing wrong here... is there any alternative way of doing this ?
It would be great if you can support with a vanillaJs answer.
For a snake game, you want the character to move even when no key is pressed.
So you need to store the direction somehow.
here's an updated version:
https://jsfiddle.net/wmvqgku4/1/
JS:
var posX = 200;
var posY = 160;
var ele = document.getElementById("snake");
const UP =0;
const RIGHT =1;
const DOWN =2;
const LEFT =3;
var dir = 1;
window.addEventListener("keydown", (key) => {
keyhandler(key.key)
});
window.onload = function () {
ele = document.getElementById("snake");
ele.style.top = posY + "px";
ele.style.left = posX + "px";
setInterval( automove, 300);
console.log("Started.");
}
function keyhandler(keys) {
try {
if (posX >= 380) {
clearInterval(movement);
}
if (keys === "ArrowRight") {
dir = RIGHT;
} else if (keys === "ArrowLeft") {
dir = LEFT;
} else if (keys === "ArrowUp") {
dir = UP;
} else if (keys === "ArrowDown") {
dir = DOWN;
} else {
console.log("invalid command: " + keys);
}
} catch (error) {
console.log("Error: " + error);
}
}
function automove() {
switch ( dir ) {
case UP: posY--; break;
case DOWN: posY++; break;
case LEFT: posX--; break;
case RIGHT: posX++; break;
}
console.log(dir);
ele.style.top = posY + "px";
ele.style.left = posX + "px";
}
CSS:
.canvas {
position: relative;
width: 500px;
height: 500px;
background-color: rgba(203, 200, 200, 0.51);
}
.snake {
width: 18px;
height: 18px;
position: absolute;
background-color: rgba(180, 9, 180, 0.808);
border-radius: 25px;
}
I made the snake position absolute, and als kept track of the x/y position, so you can add checks for the bounds.
I also changed it a bit, the keyhandler checks the keys and updates the direction variable.
the automove now only checks the direction, and updates the position.
Hope this helps.

checkCollision function is not working in Array.forEach (check elements collision)

why my checkCollision function is not working in foreach loop ? I want to check whether obs (obstacle) is hits/overlaps on collector (gray object). I am checking every 1 millisecond using setInterval checkCollision function. Basically I am trying to build a simple car game. please help me and thank you in advance
let body = document.body[0];
let container = document.querySelector(".container");
let allObstacles = [];
let colors = ["green", "green", "red"];
let collector = document.getElementById("collector");
class Obstacle {
constructor(yPos) {
this.yPos = -50;
}
randomnum() {
let randX = Math.floor(Math.random() * (container.clientWidth - 50));
return randX;
}
createObstacle() {
let obstacle = document.createElement("div");
obstacle.classList.add("obstacle");
let bgColor = colors[Math.floor(Math.random() * colors.length)];
obstacle.style.width = "50px";
obstacle.style.height = "50px";
obstacle.style.position = "absolute";
obstacle.style.left = this.randomnum() + "px";
obstacle.style.top = this.yPos + "px";
obstacle.style.backgroundColor = bgColor;
obstacle.dataset.behave = bgColor;
container.appendChild(obstacle);
return obstacle;
}
element = this.createObstacle();
updatePosition() {
this.yPos += 2;
this.element.style.top = this.yPos + "px";
}
kill() {
this.element.remove();
}
}
let dropObs = setInterval(function() {
allObstacles.forEach(function(obs) {
obs.updatePosition();
});
allObstacles.forEach(function(obs) {
// why checkCollision function is not working?
if (checkCollision(obs, collector)) {
console.log("hit");
}
if (obs.yPos > container.clientHeight) {
obs.kill();
}
});
}, 10);
let generateObs = setInterval(function() {
let obs = new Obstacle();
allObstacles.push(obs);
}, 2000);
function checkCollision(obj1, obj2) {
var obj1Y = obj1.offsetTop;
var obj2Y = obj2.offsetTop;
var obj1X = obj1.offsetLeft;
var obj2X = obj2.offsetLeft;
if (
obj2Y + 100 >= obj1Y &&
obj2Y <= obj1Y + 100 &&
obj2X + 100 >= obj1X &&
obj2X <= obj1X + 100
) {
return 1;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: 0;
}
html,
body {
width: 100%;
height: 100%;
}
.container {
position: relative;
width: 100%;
height: 100%;
}
#collector {
width: 50px;
height: 100px;
background: gray;
position: absolute;
top: calc(100vh - 100px);
left: 50%;
margin-left: -25px;
}
<div class="container">
<div id="collector"></div>
</div>
The first thing you should not use setInterval for this type of animation. Use requestAnimationFrame
https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
obj1X,obj1Y comming undefined.

JavaScript - Stop laser once its in its incrementation cycle

To see a working example simply copy code into notepad++ and run in chrome as a .html file, I have had trouble getting a working example in snippet or code pen, I would have given a link to those websites if I could get it working in them.
The QUESTION is; once I fire the laser once it behaves exactly the way I want it to. It increments with lzxR++; until it hits boarder of the game arena BUT if I hit the space bar WHILST the laser is moving the code iterates again and tries to display the laser in two places at once which looks bad and very choppy, so how can I get it to work so the if I hit the space bar a second time even whilst the laser was mid incrementation - it STOPS the incrementing and simply shoots a fresh new laser without trying to increment multiple lasers at once???
below is the Code:
<html>
<head>
<style>
#blueCanvas {
position: absolute;
background-color: black;
width: 932px;
height: 512px;
border: 1px solid black;
top: 20px;
left: 20px;
}
#blueBall {
position: relative;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 10px;
border-radius: 100%;
top: 0px;
left: 0px;
}
#laser {
position: absolute;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 1px;
top: 10px;
left: 10px;
}
#pixelTrackerTop {
position: absolute;
top: 530px;
left: 20px;
}
#pixelTrackerLeft {
position: absolute;
top: 550px;
left: 20px;
}
</style>
<title>Portfolio</title>
<script src="https://ajax.googleapis.com/
ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
document.addEventListener("keydown", keyBoardInput);
var topY = 0;
var leftX = 0;
var lzrY = 0;
var lzrX = 0;
function moveUp() {
var Y = document.getElementById("blueBall");
topY = topY -= 1;
Y.style.top = topY;
masterTrack();
if (topY < 1) {
topY = 0;
Y.style.top = topY;
};
stopUp = setTimeout("moveUp()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYup();
console.log('moveUp');
};
function moveDown() {
var Y = document.getElementById("blueBall");
topY = topY += 1;
Y.style.top = topY;
masterTrack();
if (topY > 500) {
topY = 500;
Y.style.top = topY;
};
stopDown = setTimeout("moveDown()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYdown();
console.log('moveDown');
};
function moveLeft() {
var X = document.getElementById("blueBall");
leftX = leftX -= 1;
X.style.left = leftX;
masterTrack();
if (leftX < 1) {
leftX = 0;
Y.style.leftX = leftX;
};
stopLeft = setTimeout("moveLeft()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXleft();
console.log('moveLeft');
};
function moveRight() {
var X = document.getElementById("blueBall");
leftX = leftX += 1;
X.style.left = leftX;
masterTrack();
if (leftX > 920) {
leftX = 920;
Y.style.leftX = leftX;
};
stopRight = setTimeout("moveRight()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXright();
console.log('moveRight');
};
function masterTrack() {
var pxY = topY;
var pxX = leftX;
document.getElementById('pixelTrackerTop').innerHTML =
'Top position is ' + pxY;
document.getElementById('pixelTrackerLeft').innerHTML =
'Left position is ' + pxX;
};
function topStop() {
if (topY <= 0) {
clearTimeout(stopUp);
console.log('stopUp activated');
};
if (topY >= 500) {
clearTimeout(stopDown);
console.log('stopDown activated');
};
};
function leftStop() {
if (leftX <= 0) {
clearTimeout(stopLeft);
console.log('stopLeft activated');
};
if (leftX >= 920) {
clearTimeout(stopRight);
console.log('stopRight activated');
};
};
function stopConflictYup() {
clearTimeout(stopDown);
};
function stopConflictYdown() {
clearTimeout(stopUp);
};
function stopConflictXleft() {
clearTimeout(stopRight);
};
function stopConflictXright() {
clearTimeout(stopLeft);
};
function shootLaser() {
var l = document.getElementById("laser");
var lzrY = topY;
var lzrX = leftX;
fireLaser();
function fireLaser() {
l.style.left = lzrX; /**initial x pos **/
l.style.top = topY; /**initial y pos **/
var move = setInterval(moveLaser, 1);
/**continue to increment laser unless IF is met**/
function moveLaser() { /**CALL and start the interval**/
var bcrb = document.getElementById("blueCanvas").style.left;
if (lzrX > bcrb + 920) {
/**if the X axis of the laser goes beyond the
blueCanvas 0 point by 920 then stop incrementing the laser on its X
axis**/
clearInterval(move);
/**if statement was found true so stop increment of laser**/
} else {
lzrX++;
l.style.left = lzrX;
};
};
};
};
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
shootLaser();
};
if (i == 38) {
if (topY > 0) {
moveUp();
};
};
if (i == 40) {
if (topY < 500) {
moveDown();
};
};
if (i == 37) {
if (leftX > 0) {
moveLeft();
};
};
if (i == 39) {
if (leftX < 920) {
moveRight();
};
};
};
/**
!! gradual progression of opacity is overall
!! being able to speed up element is best done with setTimout
!! setInterval is constant regards to visual speed
!! NEXT STEP IS ARRAYS OR CLASSES
IN ORDER TO SHOOT MULITPLE OF SAME ELEMENT? MAYBEE?
var l = document.getElementById("laser");
lzrX = lzrX += 1;
l.style.left = lzrX;
lzrY = topY += 1;
l.style.top = lzrY;
**/
</SCRIPT>
</head>
<div id="blueCanvas">
<div id="laser"></div>
<div id="blueBall">
</div>
</div>
<p id="pixelTrackerTop">Top position is 0</p>
<br>
<p id="pixelTrackerLeft">Left position is 0</p>
</body>
</html>
Solved the problem with using a variable called "g" and incrementing it once the laser is shot!
var g = 0;
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
if (g < 1) {
shootLaser();
g++;
};
};

Categories