js keybourd function - event is undefined - javascript

what wrong in this code? why console.log(evt) returns 'undefined'?
this is my code:
var documentKeydown = (evt)=>{
console.log(evt);
if (counter == 0) {
XWhenDown = currentX;
YWhenDown = currentY;
document.onkeyup = documentKeyup();
switch (evt.keyCode) {
case 37 : currentX -= 10; break;
case 38 : currentY -= 10; break;
case 39 : currentX += 10; break;
case 40 : currentY += 10; break;
}
animationTick = Ticker.add(animation);
}
}
document.onkeydown = documentKeydown();

You should call your function only when an event happens:
var documentKeydown = ()=>{
console.log(event);
if (counter == 0) {
XWhenDown = currentX;
YWhenDown = currentY;
document.onkeyup = documentKeyup();
switch (event.keyCode) {
case 37 : currentX -= 10; break;
case 38 : currentY -= 10; break;
case 39 : currentX += 10; break;
case 40 : currentY += 10; break;
}
animationTick = Ticker.add(animation);
}
}
document.addEventListener('keydown', documentKeydown) ;

it will be document.onkeydown = documentKeydown;
not document.onkeydown = documentKeydown();
documentKeydown is a function so do not need add () to call
var documentKeydown = (evt)=> {
console.log(evt);
}
document.onkeydown = documentKeydown;
<input type="text"/>

Related

Rotation in snake game using Javascript

I am learning javascript and making a snake game. I am stuck with rotation. The rotation happens on the whole snake element which is the exact thing I am doing and it looks very bad and I am lost of ideas that makes the animation look good.
code:
let direction = 'right';
let snakearray = [1,2,3];
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return;
}
switch (event.key) {
case "ArrowDown":
if(direction === 'up')
{
return;
}
direction = 'down'
rotateSnake(direction);
break;
case "ArrowUp":
if(direction === 'down')
{
return;
}
direction = 'up'
rotateSnake(direction);
break;
case "ArrowLeft":
if(direction === 'right')
{
return;
}
direction = 'left';
rotateSnake(direction);
break;
case "ArrowRight":
if(direction === 'left')
{
return;
}
direction = 'right'
rotateSnake(direction);
break;
default:
return;
}
event.preventDefault();
}, true);
move = function (direction, distance) {
let topOrleft = direction == 'left' || direction == 'right' ? 'left' : 'top';
let snake = document.getElementById('snake');
if (direction == 'left' || direction == 'up') {
distance *= -1;
}
let snakeBoundingRect = snake.getBoundingClientRect();
let snakeCurrentCoordinates = direction === 'left' || direction === 'right' ? snakeBoundingRect.left : snakeBoundingRect.top;
snake.style[topOrleft] = (snakeCurrentCoordinates + distance) + 'px';
}
drawSnake = function()
{
for (let index = 0; index < snakearray.length; index++) {
let span = document.createElement('span');
let snake = document.getElementById('snake');
span.style.left = 0 + (index * -16) + 'px';
span.style.top = '0px';
span.classList.add('square');
span.id = 'id-' + (index + 1);
snake.appendChild(span);
snake.style.position = 'absolute';
}
}
rotateSnake = function(direction)
{
let snake = document.getElementById('snake');
let snakenodes = document.getElementById('snake').childNodes;
console.log(snakenodes);
let rotation = null;
switch(direction)
{
case 'down':
rotation = 'rotate(90deg)';
break;
case 'up':
rotation = 'rotate(270deg)';
break;
case 'left':
rotation = 'rotate(180deg)';
break;
case 'right':
rotation = 'rotate(0deg)';
break;
}
snake.style.transform = rotation;
}
drawSnake();
let moveInterval = setInterval(() => move(direction, 5), 1000 / 5);
<!DOCTYPE html>
<html>
<head>
<title>Snake Movements</title>
<style>
.square {
position: absolute;
height: 15px;
width: 15px;
background-color: blue;
}
</style>
</head>
<body>
<span id="snake"></span>
</body>
</html>
help me with the rotation of the snake with code explanation, thank you.
you are trying to rotate whole snake, i think that is a bad idea, you need to rotate each of pieces.
function dibujar() {
let apple = new Apple(Math.random(),Math.random());
console.log('Aples '+apple.position.x);
if (contador === snake.size) {
snake.body.splice(0, 1);
contador = snake.size - 1;
}
if (contador < snake.size) {
contador++;
if (direccion === 0) {
y += -10;
snake.move(x, y);
}
if (direccion === 1) {
x += 10;
snake.move(x, y);
}
if (direccion === 2) {
y += 10;
snake.move(x, y);
}
if (direccion === 3) {
x += -10;
snake.move(x, y);
}
}
ctx.fillStyle = pat;
ctx.fillRect(area.x1, area.y1, area.x2, area.y2);
ctx.fillStyle = "rgb(255,100,0)";
ctx.beginPath();
area.paintTerrain(ctx, area.x2, area.y2, "rgb(36,23,23)");
ctx.fillRect(apple.position.x,apple.position.y,10,10);
for (let i = 0; i < snake.body.length; i++) {
ctx.fillRect(snake.body[i].x, snake.body[i].y, x2/50, y2/50);
}
}
move(stepX, stepY) {
let paso = {};
paso.x = stepX;
paso.y = stepY;
this.body.push(paso);
}

How to make this object move faster

In my code I make an object (A man sprite) move 1 pixel every time an arrow key is pressed. When you hold down the arrow key, the man is very very slow. I tried increasing the amount each time the key is pressed but that is not smooth enough. Can somebody tell me how I can make him move one pixel each time but move one pixel every 100 milliseconds? Thanks I appreciate the help.
function moveLeft() {
var newLeft = left - 1;
left = newLeft;
myElement.style.left = newLeft + 'px';
}
function moveUp() {
var newTop = topStyle - 1;
topStyle = newTop;
myElement.style.top = newTop + 'px';
}
function moveRight() {
var newLeft2 = left + 1;
left = newLeft2;
myElement.style.left = newLeft2 + 'px';
}
function moveDown() {
var newTop2 = topStyle + 1;
topStyle = newTop2
myElement.style.top = newTop2 + 'px';
}
try it, i just re-write the whole code for you. now i use an interval for each 100 milliseconds
var myElement = document.getElementById("character");
var move_left = false;
var move_up = false;
var move_right = false;
var move_down = false;
setInterval(function (){
if (move_left) myElement.style.left = (getIntfromStyle(myElement.style.left) - 1) + 'px';
if (move_up) myElement.style.top = (getIntfromStyle(myElement.style.top) - 1) + 'px';
if (move_right) myElement.style.left = (getIntfromStyle(myElement.style.left) + 1) + 'px';
if (move_down) myElement.style.top = (getIntfromStyle(myElement.style.top) + 1) + 'px';
}, 100);
// with this function, you dont need topStyle & left variables to store previous positions
// you can get current positioin easilysily
function getIntfromStyle(in_style) {
return parseInt(in_style.replace('px', ''));
}
// i use keyboard to tell code when character should be moved and when must stop
document.onkeydown = function(e) {
e = e || window.event;
switch(e.which || e.keyCode) {
case 37: // left
move_left = true;
break;
case 38: // up
move_up = true;
break;
case 39: // right
move_right = true;
break;
case 40: // down
move_down = true;
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
document.onkeyup = function(e) {
e = e || window.event;
switch(e.which || e.keyCode) {
case 37: // left
move_left = false;
break;
case 38: // up
move_up = false;
break;
case 39: // right
move_right = false;
break;
case 40: // down
move_down = false;
break;
}
}
<div id="character" style="background:red;width:20px;height:20px;position:fixed;display:block;left:0;top:0"></div>

Image stops for a second while switching arrow keys

I have another question. When I move the main player image Left or Right it moves great except for when you are moving right and then you hurry and press the left key while the right key is still down, the image stops for a second and then it decides to move left. Vise-Versa.
Main.js
var getPlatF1POSX = 0;
var getPlatF1POSY = 0;
var addVar = 0;
var addVar2 = 0;
var addVar3 = 0;
function loadGame() {
document.getElementsByTagName("DIV")[4].style.visibility = "visible";
addEventListener('mousemove', getData, false);
addEventListener('keydown', movePlayer, false);
addEventListener('keyup', stopPlayer, false);
movePlat();
moveP();
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
}
function getData(gData) {
}
var thisThis = 1;
var moveBlock1 = 350;
var stLandT = 0;
var gPos = "";
var rightPos = false;
var leftPos = false;
function movePlat() {
}
function movePlayer(mPlayer) {
switch (mPlayer.keyCode) {
case 39: // RIGHT
if (stLandT == 0 && gPos == "" && rightPos == false) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
gPos = "RIGHT";
rightPos = true;
leftPos = false;
break;
case 37: // LEFT
if (stLandT == 0 && gPos == "" && leftPos == false) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
gPos = "LEFT";
rightPos = false;
leftPos = true;
break;
case 38: // UP
break;
case 40: // DOWN
break;
}
}
function stopPlayer(sPlayer) {
switch (sPlayer.keyCode) {
case 39:
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
gPos = "";
rightPos = false;
leftPos = false;
break;
case 37:
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
gPos = "";
rightPos = false;
leftPos = false;
break;
}
}
Move Land And Player
var cTAdd = 0;
var setThis = 1;
var GAPlayer = 3;
function landT() {
setThis = setTimeout(landT, 500);
if (xPos >= 500) {
cTAdd = Math.floor(Math.random() * 100 + 1);
var block00 = document.createElement("img");
if (cTAdd > 0 && cTAdd < 25) {
block00.src = "images/sep2.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block00.src = "images/sep1.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block00.src = "images/platform00.png";
}
document.getElementById("land01").appendChild(block00);
var block01 = document.createElement("img");
var getB = block01.getBoundingClientRect();
if (cTAdd > 0 && cTAdd < 25) {
block01.src = "images/platform00.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block01.src = "images/sep2.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block01.src = "images/sep1.png";
}
document.getElementById("land00").appendChild(block01);
GAPlayer = GAPlayer + 2;
}
}
var thisSet = 1;
var cPlayer = 0;
var moveSpeed = 5;
var xPos = 50;
var yPos = 300;
function moveLand() {
thisSet = setTimeout(moveLand, 30);
if (xPos >= 500) {
moveBlock1 = moveBlock1 - 10;
document.getElementById("land00").style.left = moveBlock1 + "px";
document.getElementById("land01").style.left = moveBlock1 + "px";
}
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
function moveP() {
var setThis = setTimeout(moveP, 10);
if (leftPos == false) {
xPos = xPos + moveSpeed;
}
if (rightPos == false) {
xPos = xPos - moveSpeed;
}
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
if (xPos >= 500) {
xPos = 500;
}
if (xPos <= 50) {
xPos = 50;
}
}
This is because you stop your player no matter what key is up. You should store what key down is last pressed, than on key up you need to check if last key is released.
It was hard to me to debug your code, so I made it in jQuery (and had same troubles as you had):
var game = {
settings: {
moveSpeed: 5, // 5 milliseconds, 200fps
moveBy: 2 // 2 pixels
},
land: null,
landWidth: null,
landLeft: null,
viewport: null,
viewportWidth: null,
landMinLeft: null,
init: function() {
game.land = $('.land');
game.landWidth = game.land.width();
game.landLeft = game.land.position().left;
game.viewport = $('.viewport');
game.viewportWidth = game.viewport.width();
game.landMinLeft = -(game.landWidth-game.viewportWidth);
},
movingInterval: null,
lastKey: null,
keyDown: function (e) {
switch (e.keyCode) {
case 39: // RIGHT
game.lastKey = e.keyCode;
clearInterval( game.movingInterval );
game.movingInterval = setInterval( function() {
game.move('right');
}, game.settings.moveSpeed);
break;
case 37: // LEFT
game.lastKey = e.keyCode;
clearInterval( game.movingInterval );
game.movingInterval = setInterval( function() {
game.move('left');
}, game.settings.moveSpeed);
break;
}
},
keyUp: function(e) {
if( e.keyCode==game.lastKey ) {
game.stopMoving();
};
},
move: function( direction ) {
switch( direction ) {
case 'left':
var newLeft = game.land.position().left+game.settings.moveBy;
if( newLeft>0 ) newLeft=0;
game.land.css({
'left': newLeft+'px'
});
break;
case 'right':
var newLeft = game.land.position().left-game.settings.moveBy;
if( newLeft<game.landMinLeft ) newLeft=game.landMinLeft;
game.land.css({
'left': newLeft+'px'
});
break;
};
},
stopMoving: function() {
clearInterval( game.movingInterval );
}
};
game.init();
$(window).on('keydown', game.keyDown);
$(window).on('keyup', game.keyUp);
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body, html, .viewport {
width: 100%;
height: 100%;
}
.viewport {
position: relative;
overflow: hidden;
}
.land {
position: absolute;
left: 0;
top: 0;
width: 2300px;
height: 200px;
background: url('//dummyimage.com/2300x400/000/fff&text=Mario+is+great!+Mario+is+our+hero!+We+love+you+mario!') no-repeat center center;
background-size: cover;
will-change: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="viewport">
<div class="land"></div>
</div>
Also on Playground.
This is how you do it in Javascript/HTML5
theGame.js
var getPlatF1POSX = 0;
var getPlatF1POSY = 0;
var addVar = 0;
var addVar2 = 0;
var addVar3 = 0;
var thisThis = 1;
var moveBlock1 = 350;
var stLandT = 0;
var moveRight = false;
var moveLeft = false;
var movePL = 0;
var movePR = 0;
//////////////////////////////////////////////////////////
//
// LOAD PLATFORMS/SET KEY UP AND DOWN/SET PLAYER POS
function loadGame() {
document.getElementsByTagName("DIV")[4].style.visibility = "visible";
addEventListener('mousemove', getData, false);
addEventListener('keydown', movePlayer, false);
addEventListener('keyup', stopPlayer, false);
moveP();
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
}
function getData(gData) {
}
//////////////////////////////////////////////////////////
//
// KEY DOWN TO MOVE PLAYER
function movePlayer(mPlayer) {
switch (mPlayer.keyCode) {
case 39: // RIGHT
if (stLandT == 0) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
movePL = 0;
movePR = 1;
break;
case 37: // LEFT
if (stLandT == 0) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
movePL = 1;
movePR = 0;
break;
case 38: // UP
break;
case 40: // DOWN
break;
}
}
//////////////////////////////////////////////////////////
//
// KEY UP TO STOP PLAYER/VOID STOP AND GO GLITCH
function stopPlayer(sPlayer) {
if (sPlayer.keyCode == 39) {
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
movePR = 0;
}
if (sPlayer.keyCode == 37) {
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
movePL = 0;
}
}
landThis.js/ MOVE PLAYER AND PLATFORMS
var cTAdd = 0;
var setThis = 1;
var GAPlayer = 3;
//////////////////////////////////////////////////////////
//
// SHOW PLATFORMS TO MOVE
function landT() {
setThis = setTimeout(landT, 500);
if (xPos >= 500) {
cTAdd = Math.floor(Math.random() * 100 + 1);
var block00 = document.createElement("img");
if (cTAdd > 0 && cTAdd < 25) {
block00.src = "images/sep2.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block00.src = "images/sep1.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block00.src = "images/platform00.png";
}
document.getElementById("land01").appendChild(block00);
var block01 = document.createElement("img");
var getB = block01.getBoundingClientRect();
if (cTAdd > 0 && cTAdd < 25) {
block01.src = "images/platform00.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block01.src = "images/sep2.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block01.src = "images/sep1.png";
}
document.getElementById("land00").appendChild(block01);
GAPlayer = GAPlayer + 2;
}
}
//////////////////////////////////////////////////////////
//
// MOVE PLATFORMS
var thisSet = 1;
var cPlayer = 0;
var moveSpeed = 5;
var xPos = 50;
var yPos = 300;
function moveLand() {
thisSet = setTimeout(moveLand, 30);
if (xPos >= 500) {
moveBlock1 = moveBlock1 - 10;
document.getElementById("land00").style.left = moveBlock1 + "px";
document.getElementById("land01").style.left = moveBlock1 + "px";
}
}
//////////////////////////////////////////////////////////
//
// MOVE PLAYER
var setP = 1;
function moveP() {
setP = setTimeout(moveP, 10);
if (movePR == 1) {
xPos = xPos + moveSpeed;
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
if (movePL == 1) {
xPos = xPos - moveSpeed;
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
if (xPos >= 500) {
xPos = 500;
}
if (xPos <= 50) {
xPos = 50;
}
}

Javascript: Assigning keys to Two Different Objects on One Canvas

I want to put two different colored rectangles on one canvas and assign different keyboard keys to use each separately . Unfortunately it only works for one of them. Here is my code. I added different variables for each object, but still the other one doesn't appear. Should I apply something to the function or with the window.onload?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var GAME_SPEED = 1000/60; //game rate
var x = 100;
var y = 100;
var sideLength = 10;
var leftKey = false;
var rightKey = false;
var upKey = false;
var downKey = false;
var spaceKey = false;
var aKey = false;
var sKey = false;
var wKey = false;
var dKey = false;
var enterKey = false;
var bX = 100;
var bY = 100;
var sideLengthZ = 10;
window.onload = function()
{
c = document.getElementById("myCanvas");
c.width = window.innerWidth*0.9;
c.height = window.innerHeight*0.9;
window.setInterval("draw()" , GAME_SPEED);
}
document.onkeyup = function(event)
{
switch(event.keyCode)
{
case 37: leftKey =false;
break;
case 39: rightKey = false;
break;
case 38: upKey = false;
break;
case 40: downKey = false;
break;
case 32: spaceKey = false;
break;
case 65: aKey =false;
break;
case 83: sKey = false;
break;
case 68: dKey = false;
break;
case 87: wKey = false;
break;
case 13: enterKey = false;
break;
}
}
document.onkeydown = function(event)
{
switch(event.keyCode)
{
case 37: leftKey =true;
break;
case 39: rightKey = true;
break;
case 38: upKey = true;
break;
case 40: downKey = true;
break;
case 32: spaceKey = true;
break;
case 65: aKey =true;
break;
case 83: sKey = true;
break;
case 68: dKey = true;
break;
case 87: wKey = true;
break;
case 13: enterKey = true;
break;
}
}
function draw()
{
if(leftKey == true)
{
x--;
}
if(rightKey == true)
{
x++;
}
if(upKey == true)
{
y--;
}
if(downKey == true)
{
y++;
}
if(spaceKey == true)
{
sideLength++;
}
var c = document.getElementById("myCanvas");
var cntxt = c.getContext("2d");
cntxt.fillStyle= "#FF0000";
cntxt.fillRect(x, y, sideLength, sideLength);
}
function draw2()
{
if(aKey == true)
{
bX--;
}
if(dKey == true)
{
bX++;
}
if(wKey == true)
{
bY--;
}
if(sKey == true)
{
bY++;
}
if(enterKey == true)
{
sideLengthZ++;
}
var b = document.getElementById("myCanvas");
var cntxt2 = b.getContewxt("2d");
cntxt2.fillStyle= "#F00000";
cntxt2.fillRect(bX, bY, sideLengthZ, sideLengthZ);
}
</script>
</head>
<body>
<!--Marlon Jacques -->
<canvas id="myCanvas" style="border: 5px solid
#000000;">
Your browser does not support the canvas element.
</canvas>
</body>
</html>
You have a number of problems in your code. The first is that you were never calling the draw2 function. The second is that you were trying to use two different contexts. It is best to use only one global context.
The fixed code is below.
var GAME_SPEED = 1000 / 60; //game rate
var x = 100;
var y = 100;
var sideLength = 10;
var leftKey = false;
var rightKey = false;
var upKey = false;
var downKey = false;
var spaceKey = false;
var aKey = false;
var sKey = false;
var wKey = false;
var dKey = false;
var enterKey = false;
var bX = 100;
var bY = 100;
var sideLengthZ = 10;
var ctx;
window.onload = function() {
c = document.getElementById("myCanvas");
c.width = window.innerWidth * 0.9;
c.height = window.innerHeight * 0.9;
ctx = c.getContext('2d');
window.setInterval(function() {
draw();
draw2();
}, GAME_SPEED);
}
document.onkeyup = function(event) {
event.preventDefault();
switch (event.keyCode) {
case 37:
leftKey = false;
break;
case 39:
rightKey = false;
break;
case 38:
upKey = false;
break;
case 40:
downKey = false;
break;
case 32:
spaceKey = false;
break;
case 65:
aKey = false;
break;
case 83:
sKey = false;
break;
case 68:
dKey = false;
break;
case 87:
wKey = false;
break;
case 13:
enterKey = false;
break;
}
}
document.onkeydown = function(event) {
event.preventDefault();
switch (event.keyCode) {
case 37:
leftKey = true;
break;
case 39:
rightKey = true;
break;
case 38:
upKey = true;
break;
case 40:
downKey = true;
break;
case 32:
spaceKey = true;
break;
case 65:
aKey = true;
break;
case 83:
sKey = true;
break;
case 68:
dKey = true;
break;
case 87:
wKey = true;
break;
case 13:
enterKey = true;
break;
}
}
function draw() {
if (leftKey == true) {
x--;
}
if (rightKey == true) {
x++;
}
if (upKey == true) {
y--;
}
if (downKey == true) {
y++;
}
if (spaceKey == true) {
sideLength++;
}
ctx.fillStyle = "#FF0000";
ctx.fillRect(x, y, sideLength, sideLength);
}
function draw2() {
if (aKey == true) {
bX--;
}
if (dKey == true) {
bX++;
}
if (wKey == true) {
bY--;
}
if (sKey == true) {
bY++;
}
if (enterKey == true) {
sideLengthZ++;
}
var b = document.getElementById("myCanvas");
var cntxt2 = ctx;
ctx.fillStyle = "#F00000";
ctx.fillRect(bX, bY, sideLengthZ, sideLengthZ);
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!--Marlon Jacques -->
<canvas id="myCanvas" style="border: 5px solid
#000000;">
Your browser does not support the canvas element.
</canvas>
</body>
</html>
Here's to solve your problem and some tips:
Move the drawing of your 2nd player into draw()
You don't have to declare new canvas-variables for your 2nd player, just use the ones you had
If you want to keep some of your old code, fix the typo where you declare the context a second time var cntxt2 = b.getContewxt("2d");
function draw() {
if(leftKey == true) {
x--;
}
if(rightKey == true) {
x++;
}
if(upKey == true) {
y--;
}
if(downKey == true) {
y++;
}
if(spaceKey == true) {
sideLength++;
}
var c = document.getElementById("myCanvas");
var cntxt = c.getContext("2d");
cntxt.fillStyle= "#FF0000";
cntxt.fillRect(x, y, sideLength, sideLength);
if(aKey == true) {
bX--;
}
if(dKey == true) {
bX++;
}
if(wKey == true) {
bY--;
}
if(sKey == true) {
bY++;
}
if(enterKey == true) {
sideLengthZ++;
}
cntxt.fillStyle= "#F00000";
cntxt.fillRect(bX, bY, sideLengthZ, sideLengthZ);
}

Javascript onkeyup/onkeydown input

I am playing with a very simple little shooter to learn about easeljs, tweenjs, and canvas coding. I've run into a problem that's stumped me.
I get an unexpected end of input error in Chrome and it indicates line 1. Whats up with that?
Note that in the code below I have commented out all of the keyboard input code. The error no longer appears. When I uncomment either the document.addEventListener or window.addEventListener input code the error is thrown again. And further experimentation led me to believe it has to do with the event object but beyond that I have no idea.
Hope someone can help!
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
init();
}
function init() {
console.log("init hit");
canvas = document.getElementById("canvas");
stage = new Stage(canvas);
createStarField();
shipImg = new Image();
shipImg.onload = onShipLoaded;
shipImg.src = "ship1.png";
Ticker.setFPS(30);
Ticker.addListener(window);
/* document.addEventListener('keydown', function(event) {
switch(event.keyCode) {
case 37: // left
moveLeft = true; moveRight = false;
break;
case 38: moveUp = true; moveLeft = false;
break;
case 39: moveRight = true; moveLeft = false;
break;
case 40: moveDown = true; moveUp = false;
break;
}
}, false);
document.addEventListener('keyup', function() {
switch(e.keyCode) {
// left
case 37: moveLeft = false;
break;
// up
case 38: moveUp = false;
break;
// right
case 39: moveRight = false;
break;
// down
case 40: moveDown = false;
break;
}
}, false);
*/
/*function onKeyDown(e) {
//if(!e) { var e = window.event; }
switch(e.keyCode) {
// left
case 37: moveLeft = true; moveRight = false;
break;
case 38: moveUp = true; moveLeft = false;
break;
case 39: moveRight = true; moveLeft = false;
break;
case 40: moveDown = true; moveUp = false;
break;
}
}
function onKeyUp(e) {
// if(!e) { var e = window.event; }
switch(e.keyCode) {
// left
case 37: moveLeft = false;
break;
// up
case 38: moveUp = false;
break;
// right
case 39: moveRight = false;
break;
// down
case 40: moveDown = false;
break;
}
*/
function checkMovement() {
if(moveLeft)
{
ship.x -= speed;
if(ship.x < 0)
ship.x = 640;
}
else if(moveRight)
{
ship.x += speed;
if(ship.x > 640)
ship.x = 0;
}
if(moveUp)
{
if(ship.y - speed > 24)
ship.y -= speed;
}
else if(moveDown)
{
if(ship.y + speed < 460)
ship.y += speed;
}
}
function onShipLoaded() {
ship = new Bitmap(shipImg);
ship.regX = ship.image.width * .05;
ship.regY = ship.image.height * 0.5;
ship.x = 320;
ship.y = 450;
stage.addChild(ship);
}
function createStarField() {
console.log("create star field");
stars = new Array();
g = new Graphics();
g.setStrokeStyle(1);
g.beginStroke(Graphics.getRGB(255,255,255));
g.beginFill(Graphics.getRGB(255,255,255));
g.drawCircle(0,0,1);
for(var i = 0; i < 100; ++i) {
var s = new Shape(g);
stars.push(s);
s.x = randRange(10,630);
s.y = randRange(-250, 470);
s.scaleX = randRange(0.5, 2);
s.scaleY = s.scaleX;
s.alpha = Math.random() + 0.2;
stage.addChild(s);
}
}
function randRange(min, max) {
return Math.floor(Math.random()*(max - min)) + min;
}
function tick() {
console.log("tick hit");
updateStarField();
checkMovement();
stage.update();
}
function updateStarField() {
console.log("updateStarField()");
var curStar;
var limit = stars.length;
for(var i = 0; i < limit; ++i) {
curStar = stars[i];
curStar.y += 4
if(curStar.y > 480) {
curStar.x = randRange(10,630);
curStar.y = -randRange(20, 450);
}
}
}
The last commented out onKeyUp(e) function lacks a closing curly brace (})

Categories

Resources