Javascript Letter Key Binding - javascript

I am trying to make these events happen when the D key ( for right movement ) and the A key ( for left movement ) but when I enter their correct key codes in the correct places it does not function when I press the D or S key to move. Can anyone tell me what is wrong? I'm using a recent version of Mozilla FireFox but I don't believe it's a requestAnimFrame problem.
document.onkeydown = function(e)
{
e = e || window.event;
switch(e.which || e.keyCode)
{
case 37:
leftpress = true;
Context.clearRect( 0, 0, CanWidth, CanHeight ); // Clear the Canvas
Context.fillStyle = 'green';
OldBackgroundX = BackgroundX;
BackgroundX = BackgroundX + 5;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
Context.fillText( "You move left.", 200, 100 );
leftanimate = true;
if ( jumppress == true )
{
leftjump = true;
}
break;
// case 38:
// jump();
// up/jump
//break;
case 39:
if ( rightpress == true )
{
rightanimate = true;
}
/*console.log("You move right");
Context.fillStyle = 'green';
OldBackgroundX = BackgroundX;
BackgroundX = BackgroundX - 20;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
Context.drawImage( ArrowRightImg, 400, 200 );// right
Context.fillText( "You move right.", 200, 100 );
break;
case 40: // down*/
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
};
document.onkeypress = function(event)
{
event = event || window.event;
switch(event.which || event.keyCode)
{
case 32:
jumppress = true;
if ( jumppress == true )
{
PJ = true;
}
if ( rightpress == true )
{
archjump = true;
}
if ( leftpress == true )
{
leftjump = true;
}
// up/jump
break;
/*
*
* Player Right Animation
*
*
* */
var Animation;
case 39:
rightpress = true;
if ( rightpress == true )
{
Context.clearRect( 0, 0, CanWidth, CanHeight ); // Clear the Canvas
//console.log("You move right");
Context.fillStyle = 'green';
BackgroundX = BackgroundX - 5;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
rightanimate = true;
if ( jumppress == true )
{
archjump = true;
}
}
break;
}
}
document.onkeyup = function(event)
{
event = event || window.event;
switch(event.which || event.keyCode)
{
case 32:
jumppress = false;
break;
case 39:
rightpress = false;
break;
case 37:
leftpress = false;
}
}

You are using the wrong key codes to bind to WASD; the codes you are using correspond to the arrow keys themselves.
var KEY = {
WASD_LEFT: 65,
WASD_RIGHT: 68,
WASD_UP: 87,
WASD_DOWN: 83
}
document.onkeydown = function (e) {
switch (e.keyCode) {
case KEY.WASD_LEFT:
alert('Left');
break;
case KEY.WASD_RIGHT:
alert('Right');
break;
case KEY.WASD_UP:
alert('Up');
break;
case KEY.WASD_DOWN:
alert('Down');
break;
default:
return; // exit this handler for other keys
}
};
Here's a nice reference for JS key codes, and a fiddle for funsies.

Related

JS Canvas game using keypress event to modify speed when holding shift button

I am learning how to make a game with the canvas via JavaScript, and I have the arrow keys set to move a block on the canvas. I want to add a modifier in which while holding shift, the block moves twice as fast, and I cannot get my function to work properly when the shift key is pressed.
Any suggestions/help would be much appreciated!
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 540;
this.canvas.height = 330;
this.context = this.canvas.getContext("2d");
document.body.appendChild(this.canvas,document.body.childNodes[0]);
this.canvas.setAttribute("id", "myCanvas");
this.canvas.hidden = true;
this.interval = setInterval(updateGameArea, 1000/FPS);
window.addEventListener('keydown', function (e) {
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -10; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 10; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -10; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 10; }
if (myGameArea.keys && myGameArea.keys[65]) {myGamePiece.speedX = -10; }
if (myGameArea.keys && myGameArea.keys[68]) {myGamePiece.speedX = 10; }
if (myGameArea.keys && myGameArea.keys[87]) {myGamePiece.speedY = -10; }
if (myGameArea.keys && myGameArea.keys[83]) {myGamePiece.speedY = 10; }
//What do I need to do to get the following function to execute? (NOTE
//THIS WAS MOVED TO AFTER IF STATEMENTS PER COMMENT BELOW, THIS DID NOT
/////FIX the ISSUE)
GetShiftState(e);
myGamePiece.newPos();
myGamePiece.update();
}
//Below is the get shift key function I cannot get to work.
//What I am trying to do is increase the speed of the gamepiece moving
//when holding shift + the directional arrow
function GetShiftState (e) {
if (e.shiftKey) {
switch(e.which) {
case 37:
console.log("shift + left arrow");
myGamePiece.speedX = -20;
break;
case 38:
console.log("shift + up arrow");
myGamePiece.speedY = -20;
break;
case 39:
console.log("shift + right arrow");
myGamePiece.speedX = 20;
break;
case 40:
console.log("shift + down arrow");
myGamePiece.speedY = 20;
break;
default:
break;
}
}
else {
console.log("Shift key is up.");
}
}
You are resetting the myGamePiece.speed to 10 after you call the method.
Move the function call to after the end of the if statements.
Below is a snippet from some code I wrote for moving a div around the screen.
The principle is the same though, note we have a step variable and we adjust it if the event.shiftKey is true.
Complete code can be viewed / forked here: https://repl.it/#PaulThomas1/MoveDivAroundTheScreen
var step = 10;
if (event.shiftKey) step = step * 2;
switch (key) {
case "ArrowUp":
event.preventDefault();
box.style.top = (top - step) + "px";
break;
case "ArrowDown":
event.preventDefault();
box.style.top = (top + step) + "px";
break;
case "ArrowLeft":
box.style.left = (left - step) + "px";
break;
case "ArrowRight":
box.style.left = (left + step) + "px";
break;
}

Continuously drawing rectangles in JavaScript canvas slows the program after a few seconds

Right now I'm trying to make a simple 2D platformer in JavaScript canvas. This is what I have so far:
<!DOCTYPE html>
<html>
<body>
<style>
canvas{
background: #eee;
}
</style>
<canvas id="ctx" tabindex=0 width=900 height=500 style="border:1px solid #000000;" onkeypress="movePlayer(event)" onkeyup="keyUp(event)"></canvas>
<script>
var canvas = document.getElementById("ctx");
var ctx = canvas.getContext("2d");
canvas.setAttribute('tabindex', 0);
canvas.focus();
canvas.addEventListener("keydown", movePlayer);
//Maybe I can get a class working?
function Platform(x,y,xSize,ySize){
this.xPos = x;
this.yPos = y;
ctx.fillStyle = "red";
ctx.fillRect(x,y,xSize,ySize);
this.getX = function(){
return this.xPos;
};
this.getY = function(){
return this.yPos;
};
this.getxSize = function(){
return this.xSize;
};
this.getySize = function(){
return this.ySize;
};
}
//Function arrays?
platformArray = [];
//Too many vars smh:
var x_previous = 50;
var y_previous = 50;
var x_new = 50;
var y_new = 50;
var isJumping = false;
var isColliding = false;
var right = false;
var left = false;
var up = false;
var down = false;
var speed = 5;
function movePlayer(event) {
switch(event.keyCode){
//Right
case 39:
right = true;
break;
//Left
case 37:
left = true;
break;
//Up
case 38:
isJumping = true;
up = true;
break;
}
}
function keyUp(event){
switch(event.keyCode){
//Up key up:
case 38:
isJumping = false;
up = false;
break;
//Right key up:
case 39:
right = false;
break;
//Left key up:
case 37:
left = false;
break;
//Down key up:
case 40:
down = false;
break;
}
}
setInterval(update,1);
setTimeout(update,1)
function boundsIntersect(x1,y1,x2,y2){
if(x1 > x2-20 && x1 < x2+200 && y1 < y2 && y1 > y2-55){
return true;
}
return false;
}
function update(){
ctx.clearRect(0,0,900,500)
ctx.fillStyle = "black";
ctx.beginPath();
ctx.fillRect(x_new,y_new,50,50);
//Draw ground:
ctx.beginPath();
ctx.rect(0,490,900,10);
ctx.fillStyle = "green";
ctx.fill();
if(right == true){
x_new+=speed;
x_previous=x_new-speed;
} else if(left == true){
x_new-=speed;
x_previous=x_new-speed;
} else if(down == true){
y_new+=speed;
y_previous=y_new-speed;
} else if(up == true){
y_new-=speed;
y_previous=y_new-speed;
}
if(y_new < 440 && isJumping == false && isColliding == false){
y_new+=5;
y_previous=y_new-5;
}
//Platforms:
platform1 = new Platform(50,300,200,10);
platformArray.push(platform1);
platform2 = new Platform(300,200,200,10);
platformArray.push(platform2);
platform3 = new Platform(400,300,200,10);
platformArray.push(platform3);
//Platform intersections:
platformArray.forEach(function(platform){
if(boundsIntersect(x_new,y_new,platform.getX(), platform.getY()) && isJumping == false){
isColliding = true;
y_new -= 0.5;
} else if(boundsIntersect(x_new,y_new,platform.getX(), platform.getY()) && isJumping == true){
isJumping = false;
y_new += 10;
isColliding = true;
} else {
isColliding = false;
}
});
ctx.save();
ctx.restore();
}
update();
</script>
</body>
</html>
The program runs just fine up until right around the 20sec mark, then it starts to run slower and slower until it just barely moves the player anymore.
I've tried every possible solution I've found online, but nothing seems to work. Any help is appreciated!
Instead of using window.interval to redraw the frames, use window.requestAnimationFrame. There is an example there how to use it.
What you're doing is trying to redraw the frames every 1/1000 of second, which is way too fast anyway.
What window.requestAnimationFrame does is it smartly requests new frames to redraw as needed, in order to maintain a smooth animation.

Rectangle class not visibly showing up on canvas

I'm trying to make a 2D platformer game, so far everything has worked, however now I'm trying to get the platforms I created to move back and forth, so I decided to create a draw() method within my Platform class in order to render the platforms:
var canvas = document.getElementById("ctx");
var ctx = canvas.getContext("2d");
canvas.setAttribute('tabindex', 0);
canvas.focus();
canvas.addEventListener("keydown", movePlayer);
//Maybe I can get a class working?
class Platform {
constructor(x, y, xS, yS, moveBool) {
this.xPos = x;
this.yPos = y;
this.xSize = xS;
this.ySize = yS;
this.moveable = moveBool;
}
draw(ctx) {
ctx.fillStyle = "red";
ctx.fillRect(this.xPos, this.yPos, this.xSsize, this.ySsize);
}
get getX() {
return this.xPos;
}
get getY() {
return this.yPos;
}
get getxSize() {
return this.xSize;
}
get getySize() {
return this.ySize;
}
get getMoveable() {
return this.moveable;
}
set moveRight(speed) {
this.xPos = speed;
}
}
//Platform array:
platformArray = [];
//Vars:
var x_new = 50;
var y_new = 50;
var isJumping = false;
var isColliding = false;
var speed = 5;
var keys = {
up: false,
right: false,
left: false
};
function movePlayer(event) {
switch (event.keyCode) {
//Right key down:
case 39:
keys["right"] = true;
break;
//Left key down:
case 37:
keys["left"] = true;
break;
//Up key down:
case 38:
keys["up"] = true;
isJumping = true;
break;
}
}
function keyUp(event) {
switch (event.keyCode) {
//Up key up:
case 38:
isJumping = false;
keys["up"] = false;
break;
//Right key up:
case 39:
keys["right"] = false;
break;
//Left key up:
case 37:
keys["left"] = false;
break;
}
}
function boundsIntersect(x1, y1, x2, y2) {
if (x1 > x2 - 50 && x1 < x2 + 200 && y1 < y2 && y1 > y2 - 55) {
return true;
}
return false;
}
function update() {
window.requestAnimationFrame(update);
ctx.clearRect(0, 0, 900, 500);
ctx.fillStyle = "black";
ctx.beginPath();
ctx.fillRect(x_new, y_new, 50, 50);
//Draw ground:
ctx.beginPath();
ctx.rect(0, 490, 900, 10);
ctx.fillStyle = "green";
ctx.fill();
//PLayer movement:
if (keys["up"] && !keys["right"] && !keys["left"]) {
y_new -= speed;
} else if (keys["right"] && !keys["up"]) {
x_new += speed;
} else if (keys["left"] && !keys["up"]) {
x_new -= speed;
} else if (keys["up"] && keys["right"]) {
y_new -= speed;
x_new += speed;
} else if (keys["up"] && keys["left"]) {
y_new -= speed;
x_new -= speed;
}
if (y_new < 440 && isJumping == false && isColliding == false) {
y_new += 5;
y_previous = y_new - 5;
}
//Platforms:
platform1 = new Platform(50, 300, 200, 10, true);
platformArray.push(platform1);
platform1.draw(ctx);
platform2 = new Platform(300, 200, 200, 10, false);
platformArray.push(platform2);
platform3 = new Platform(400, 300, 200, 10, false);
platformArray.push(platform3);
//Platform intersections:
platformArray.forEach(function(platform) {
if (boundsIntersect(x_new, y_new, platform.getX, platform.getY) && isJumping == false) {
isColliding = true;
y_new -= 0.5;
} else if (boundsIntersect(x_new, y_new, platform.getX, platform.getY) && isJumping == true) {
isJumping = false;
y_new += 11;
isColliding = true;
} else {
isColliding = false;
}
});
var platSpeed = 2;
//Move platforms:
platformArray.forEach(function(platform) {
if (platform.getMoveable) {
if (platform.getX > 0) {
platform.moveRight = 300;
platform.draw(ctx);
}
}
});
ctx.save();
ctx.restore();
}
window.requestAnimationFrame(update);
update();
canvas {
background: #eee;
}
<!DOCTYPE html>
<html>
<body>
<canvas id="ctx" tabindex=0 width=900 height=500 style="border:1px solid #000000;" onkeypress="movePlayer(event)" onkeyup="keyUp(event)"></canvas>
</body>
</html>
However what happens is, the platforms are there because BoundsIntersect detects them, but they're just not visually showing up and I'm not sure why. Any help is appreciated!
Your draw function has a typo. You are also calling your update() function twice at the bottom. Here is a version with the platforms fixed. Just bear in mind that your platforms don't seem to work as you might expect. However, I think that warrants a different question.
var canvas = document.getElementById("ctx");
var ctx = canvas.getContext("2d");
canvas.setAttribute('tabindex', 0);
canvas.focus();
canvas.addEventListener("keydown", movePlayer);
//Maybe I can get a class working?
class Platform {
constructor(x, y, xS, yS, moveBool) {
this.xPos = x;
this.yPos = y;
this.xSize = xS;
this.ySize = yS;
this.moveable = moveBool;
}
draw(ctx) {
ctx.fillStyle = "red";
ctx.fillRect(this.xPos, this.yPos, this.xSize, this.ySize);
}
get getX() {
return this.xPos;
}
get getY() {
return this.yPos;
}
get getxSize() {
return this.xSize;
}
get getySize() {
return this.ySize;
}
get getMoveable() {
return this.moveable;
}
set moveRight(speed) {
this.xPos = speed;
}
}
//Platform array:
platformArray = [];
//Vars:
var x_new = 50;
var y_new = 50;
var isJumping = false;
var isColliding = false;
var speed = 5;
var keys = {
up: false,
right: false,
left: false
};
function movePlayer(event) {
switch (event.keyCode) {
//Right key down:
case 39:
keys["right"] = true;
break;
//Left key down:
case 37:
keys["left"] = true;
break;
//Up key down:
case 38:
keys["up"] = true;
isJumping = true;
break;
}
}
function keyUp(event) {
switch (event.keyCode) {
//Up key up:
case 38:
isJumping = false;
keys["up"] = false;
break;
//Right key up:
case 39:
keys["right"] = false;
break;
//Left key up:
case 37:
keys["left"] = false;
break;
}
}
function boundsIntersect(x1, y1, x2, y2) {
if (x1 > x2 - 50 && x1 < x2 + 200 && y1 < y2 && y1 > y2 - 55) {
return true;
}
return false;
}
function update() {
window.requestAnimationFrame(update);
ctx.clearRect(0, 0, 900, 500);
ctx.fillStyle = "black";
ctx.beginPath();
ctx.fillRect(x_new, y_new, 50, 50);
//Draw ground:
ctx.beginPath();
ctx.rect(0, 490, 900, 10);
ctx.fillStyle = "green";
ctx.fill();
//PLayer movement:
if (keys["up"] && !keys["right"] && !keys["left"]) {
y_new -= speed;
} else if (keys["right"] && !keys["up"]) {
x_new += speed;
} else if (keys["left"] && !keys["up"]) {
x_new -= speed;
} else if (keys["up"] && keys["right"]) {
y_new -= speed;
x_new += speed;
} else if (keys["up"] && keys["left"]) {
y_new -= speed;
x_new -= speed;
}
if (y_new < 440 && isJumping == false && isColliding == false) {
y_new += 5;
y_previous = y_new - 5;
}
//Platforms:
platform1 = new Platform(50, 300, 200, 10, true);
platformArray.push(platform1);
platform1.draw(ctx);
platform2 = new Platform(300, 200, 200, 10, false);
platformArray.push(platform2);
platform3 = new Platform(400, 300, 200, 10, false);
platformArray.push(platform3);
//Platform intersections:
platformArray.forEach(function(platform) {
if (boundsIntersect(x_new, y_new, platform.getX, platform.getY) && isJumping == false) {
isColliding = true;
y_new -= 0.5;
} else if (boundsIntersect(x_new, y_new, platform.getX, platform.getY) && isJumping == true) {
isJumping = false;
y_new += 11;
isColliding = true;
} else {
isColliding = false;
}
});
var platSpeed = 2;
//Move platforms:
platformArray.forEach(function(platform) {
if (platform.getMoveable) {
if (platform.getX > 0) {
platform.moveRight = 300;
platform.draw(ctx);
}
}
});
ctx.save();
ctx.restore();
}
window.requestAnimationFrame(update);
canvas {
background: #eee;
}
<!DOCTYPE html>
<html>
<body>
<canvas id="ctx" tabindex=0 width=900 height=500 style="border:1px solid #000000;" onkeypress="movePlayer(event)" onkeyup="keyUp(event)"></canvas>
</body>
</html>

Javascript Canvas Arched Jump

I am having an issue trying to make the main character of our class' platformer (for now it is only an arrow) jump in an arch. I've tried to make an if function inside the switch so that if both the right arrow key and if the jump button are pressed, the player will jump to the right in an arch. However, it only jumps up in a straight line. Any help? Here is my code:
var left = 37;
var up = 38;
var right = 39;
var down = 40;
var rightpress = false;
var jumppress = false;
var leftpress = false;
var CanHeight = 400;
var CanWidth = 800;
var BackgroundX = 00;
var BackgroundY = 00;
var ArrowMove = 0;
PreGame();
function preLoadImage( url )
{
image = new Image();
image.src = url;
image.onload = function( )
{
return; // return image - image was empty made global
};
}
function PreGame( )
{
preLoadImage ( "pics/arrowright.png" );
ArrowRightImg = image;
preLoadImage ( "pics/Background1.png" );
FirstBackgroundImg = image;
}
function InitGame( )
{
SetCanvas( 'classified' );
DrawScene();
//canvas.addEventListener("mousedown", doMouseDown, false);
//window.addEventListener("rightarrow", onrightarrow, false);
// Use the code below for perhaps a custom mouse cursor
//canvas.addEventListener("mouseover", doMouseOver, false);
Loop();
}
function SetCanvas( id )
{
canvas = document.createElement( 'canvas' );
var div = document.getElementById( id );
canvas.width = CanWidth;
canvas.height = CanHeight;
canvas.style.position = "absolute";
canvas.style.border = "#222222 5px solid";
div.appendChild(canvas);
Context = canvas.getContext("2d");
}
function DrawScene()
{
Context.fillStyle = 'green';
if ( ArrowMove == 0 )
{
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
}
Context.drawImage( ArrowRightImg, 400, 325 );
}
/*function doMouseDown(event)
{
canvas_x = event.pageX;
canvas_y = event.pageY;
}*/
var PlayerJump = 0;
var counter = 0;
var PJ = false;
function jump()
{
--counter;
console.log("You Jump: " + PlayerJump);
if ( PJ == true )
{
++PlayerJump;
if( PlayerJump <= 12 )
{
OldBackgroundY = BackgroundY;
BackgroundY = BackgroundY + 5;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
}
if ( PlayerJump >= 13 && PlayerJump <= 24 )
{
BackgroundY = BackgroundY - 5;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
}
Context.drawImage( ArrowRightImg, 400, 325 );// left
if ( PlayerJump >= 25 )
{
PlayerJump = 0;
PJ = false;
}
DrawScene();
}
}
document.onkeydown = function(e)
{
e = e || window.event;
switch(e.which || e.keyCode)
{
case 37:
Context.fillStyle = 'green';
console.log("You move left");
OldBackgroundX = BackgroundX;
BackgroundX = BackgroundX + 20;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
Context.drawImage( ArrowRightImg, 400, 325 );// left
Context.fillText( "You move left.", 200, 100 );
break;
document.onkeypress = function(event)
{
event = event || window.event;
switch(event.which || event.keyCode)
{
case 38:
jumppress = true;
if ( jumppress == true )
{
PJ = true;
}
if ( PlayerJump >= 1 && PlayerJump < 24 )
{
rightpress = false;
}
// up/jump
break;
case 39:
rightpress = true;
if ( rightpress == true )
{
console.log("You move right");
Context.fillStyle = 'green';
OldBackgroundX = BackgroundX;
BackgroundX = BackgroundX - 20;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
Context.drawImage( ArrowRightImg, 400, 325 );// right
Context.fillText( "You move right.", 200, 100 );
rightpress = false;
}
break;
}
if ( rightpress == true && jumppress == true )
{
//case 39:
console.log("You jump right");
Context.fillStyle = 'green';
OldBackgroundX = BackgroundX;
BackgroundX = BackgroundX - 20;
PJ = true;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
Context.drawImage( ArrowRightImg, 400, 200 );// right
//Context.fillText( "You move right.", 200, 100 );
//break;
//case 38:
if ( PlayerJump <= 24 )
{
PJ = false;
jumppress = false;
rightpress = false;
}
}
}
function UpDate()
{
if ( PJ == true )
{
jump();
}
//--counter;
//console.log("Updated");
//DrawScene();*/
}
var lastTime = 0;
var ticks = 0;
function Loop()
{
var now = Date.now();
dt = ( now - lastTime ) / 1000.0;
//console.log("fired rocket");
UpDate(); // UPDATE ALL THE GAME MOVES
//EnemyUpDate();
lastTime = now;
requestAnimFrame( Loop ); // LOOP CALLBACK
};
var requestAnimFrame =
(
function( )
{
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback )
{
window.setTimeout( callback, 1000 / 60 );
};
}
)();
Just use a simple pseudo gravity factor together with a delta value to get the classic jump behavior.
Live demo
For example, define a few variables for the movement (only for y axis, values for x included in demo):
var floor = h - img.height + 16, // fixed floor position (here based on image)
y = floor, // set initial y position = floor
dy = 0, // current delta (=0 no movement on y axis)
jump = -5, // jump strength
g = 0.5; // "gravity" strength
When a jump is initiated we set delta y (dy) equal to the jump strength. You can variate strength as you need. This will accumulate on the y value, but since the gravity (g) is polling on the delta value it will eventually reverse the value and result will be a jump.
We check that we are on the floor and when we returned to ground so-to-speak just set y to floor and clear the delta value:
// we got a jump or are in a jump
if (dy !== 0 || y !== floor) {
y += dy; // add delta
dy += g; // affect delta with gravity
if (y > floor) { // on ground?
y = floor; // reset y position
dy = 0; // and clear delta
}
}
This is a very efficient way of emulating a jump with non-expensive math operations, which can be a critical factor in a game.
You can also click (or hit a key) several times while in a jump to extend it as was very typical in the old games. You can of course prevent this simply by checking the delta value when clicking and only reset it if dy === 0
Adjust jump strength with a more negative value for jump and if you want the character faster down simply increase the gravity value g.

JavaScript collision detection not working

I am trying to make collision detection work in a JavaScript program I am working in currently, and I can't figure out why it is triggering in such strange coordinates. X 50 Y 199
If any of you good help that would be much appreciated. Here is my code.
var game = {};
game.fps = 50;
game.playerX = 50;
game.playerY = 50;
game.draw = function () {
c = document.getElementById('canvas');
ctx = c.getContext("2d");
clearCanvas();
//PLAYER
ctx.fillStyle = "blue";
ctx.fillRect(game.playerX, game.playerY, 50, 50);
//ENEMY
ctx.fillStyle = "green";
ctx.fillRect(200, 200, 50, 50);
//Coords
ctx.font = "20px Arial";
ctx.fillStyle = "red";
ctx.fillText(game.playerX, 400, 480);
ctx.fillText(game.playerY, 450, 480);
};
game.update = function () {
document.onkeydown = function () {
switch (window.event.keyCode) {
case 87:
//up
--game.playerY;
break;
case 83:
//down
++game.playerY;
break;
case 65:
//left
--game.playerX;
break;
case 68:
//right
++game.playerX;
break;
}
};
//COLLISION DETECTION
if (game.playerX <= 200 && game.playerX <= 250 && game.playerY >= 200 && game.playerY <= 250) {
alert("it worked!");
game.playerX = 400;
}
//END OF COLLISION DETECTION
};
game.run = function () {
game.update();
game.draw();
};
game.start = function () {
game._intervalId = setInterval(game.run, 1000 / game.fps);
};
game.stop = function () {
clearInterval(game._intervalId);
};
Based on your if statement in the Y axis I'd say you want if(game.playerX >= 200 rather than if(game.playerX <= 200. Right now you're checking if playerX is both less than 200 and less than 250, which 50 satisfies.
You are using the wrong keycodes: JavaScript Keycodes. Additionally, you are only running the collision check one time, when you manually call game.update(). You need to run the collision check within the keydown event:
Here is a Fiddle
document.onkeydown = function (e) {
switch (e.keyCode) {
case 38:
//up
console.log('up');
--game.playerY;
break;
case 40:
//down
++game.playerY;
break;
case 37:
//left
--game.playerX;
break;
case 39:
//right
++game.playerX;
break;
}
console.log(game.playerX + ', ' + game.playerY);
//COLLISION DETECTION
if (game.playerX >= 200 && game.playerX <= 250 && game.playerY >= 200 && game.playerY <= 250) {
alert("it worked!");
game.playerX = 400;
}
};

Categories