Move 2 images simultaniously with keyboard events? - javascript

I'm making a primitive typescript game for fun. So far everything works fine.
Player one moves around with ASWD and second player with HUJK.
These are the two events and they are declared in the constructor as so this.move(); and this.moveBug();
private move() {
window.addEventListener('keypress', (e: KeyboardEvent) => {
switch (e.keyCode) {
case 97:
this._player.move(-10, 0);
break;
case 119:
this._player.move(0, -10);
break;
case 100:
this._player.move(+10, 0);
break;
case 115:
this._player.move(0, +10);
break;
}
this.update();
});
}
private moveBug() {
window.addEventListener('keypress', (e: KeyboardEvent) => {
switch (e.keyCode) {
case 104:
this._bugPlayer.moveBug(-10, 0);
break;
case 117:
this._bugPlayer.moveBug(0, -10);
break;
case 107:
this._bugPlayer.moveBug(+10, 0);
break;
case 106:
this._bugPlayer.moveBug(0, +10);
break;
}
this.update();
});
}
However both images move turn based, I can't move them both at the same time.
I want this game to be playable on 1 keyboard.
Is there a way this can be achieved?

I would define the move function once and call it based on the pressed key. Here is a rough skeleton of the approach.
class Movement {
move(target, x, y) {
// handle move code...
}
constructor() {
const move = this.move;
window.addEventListener('keypress', (e: KeyboardEvent) => {
let charCode = e.which || e.keyCode;
switch (charCode) {
case 97:
move('player', -10, 0);
break;
case 119:
move('player', 0, -10);
break;
case 100:
move('player', +10, 0);
break;
case 115:
move('player', 0, +10);
break;
case 104:
move('bug', -10, 0);
break;
case 117:
move('bug', 0, -10);
break;
case 107:
move('bug', +10, 0);
break;
case 106:
move('bug', 0, +10);
break;
}
});
}
}
const m = new Movement();
https://jsfiddle.net/zp3vj7ma/

Related

Event .key switch for a video game

i want to change the way my Js game works, basically the game does not recognize input whenever the language is not english with no Capital letters ( only when the event.key is equal to wasd ) how can i fix this bug ?
thanks !
window.addEventListener('keydown', (event) => {
if (!player.isDead){
switch (event.key) {
case 'w':
keys.d.pressed = true;
player.lastkey = 'd';
break;
case 'a':
keys.a.pressed = true;
player.lastkey = 'a';
break;
case 'w':
if(player.position.y > 0)
{
player.velocity.y = -10;
}
break;
case ' ':
player.Attacking();
if(player.lastkey === 'd'){player.SwitchSprite('punch')}
else{player.SwitchSprite('fpunch')}
break;
}
}
You should use the event.code or event.keyCode properties to stay language independent;
switch (event.code) // <- not event.key
case "KeyW": // <- not 'w'
...

Unable to invoke JS function: Syntax mistake or eyes too crossed?

Happy holidays first of all.
I am unable to find the reason why I am unsuccessful at invoking the 'commands' function with its relative orders on this Javascript exercise. Have I messed up with the {}?
//// Rover object goes here ////
const rover = {
direction: "N",
x: 5,
y: 5,
travelLog: []
};
// ========================
//// Rover turns left switch case ////
function turnLeft(rover) {
switch (rover.direction) {
case "N":
rover.direction = "W";
break;
case "W":
rover.direction = "S";
break;
case "S":
rover.direction = "E";
break;
case "E":
rover.direction = "N";
break;
}
console.log("turnLeft was called!");
console.log(`Rover has now direction:"${rover.direction}"`);
}
//// Rover turns right switch case ////
function turnRight(rover) {
switch (rover.direction) {
case "N":
rover.direction = "E";
break;
case "W":
rover.direction = "N";
break;
case "S":
rover.direction = "W";
break;
case "E":
rover.direction = "S";
break;
}
console.log("turnRight was called!");
console.log(`Rover has now direction:"${rover.direction}"`);
}
//// Moving the rover ////
function moveForward(rover) {
console.log("moveForward was called!");
let newPosition = { x: rover.x, y: rover.y };
rover.travelLog.push(newPosition);
switch (rover.direction) {
case "N":
if (rover.y <= 0) {
console.log("you can't travel out there, bud");
} else {
rover.y--;
console.log(
`Rover moved North: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "E":
if (rover.x >= 9) {
console.log("you can't travel out there, bud");
} else {
rover.x++;
console.log(
`Rover moved East: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "S":
if (rover.y >= 9) {
console.log("you can't travel out there, bud");
} else {
rover.y++;
console.log(
`Rover moved South: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "W":
if (rover.x <= 0) {
console.log("you can't travel out there, bud");
} else {
rover.x--;
console.log(
`Rover moved West: position is now: ${rover.x} , ${rover.y}`
);
}
break;
}
}
//move backward//
function moveBackward(rover) {
console.log("moveBackward was called!");
let newPosition = { x: rover.x, y: rover.y };
rover.travelLog.push(newPosition);
switch (rover.direction) {
case "N": // Rover is facing North, but it will take one step backwards, hence direction South //
if (rover.y >= 9) {
console.log("watch your steps, don't trip");
} else {
rover.y++;
console.log(
`Rover moonwalked South: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "E": //moving direction South
if (rover.x <= 0) {
console.log("watch your steps, don't trip");
} else {
rover.x--;
console.log(
`Rover moonwalked West: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "S": // direction North
if (rover.y <= 0) {
console.log("watch your steps,don't trip");
} else {
rover.y--;
console.log(
`Rover moonwalked North: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "W": //direction East
if (rover.x >= 9) {
console.log("watch your steps, don't trip");
} else {
rover.x++;
console.log(
`Rover moonwalked East: position is now: ${rover.x} , ${rover.y}`
);
}
break;
}
//// Assigning commands ////
function commands(rover, orders) {
for (let i = 0; i < orders.length; i++) {
let order = orders[i];
switch (order) {
case "f":
moveForward(rover, order);
break;
case "b":
moveBackward(rover, order);
break;
case "r":
turnRight(rover, order);
break;
case "l":
turnLeft(rover, order);
break;
default:
console.log("Please use only 'r', 'f', 'b' or 'l'");
}
}
}
commands(rover,"ffbrl");
////printout all the rover's movements////
/*
for (let i = 0; i < rover.travelLog.length; i++) {
console.log(`Path ${i} ==> x=${rover.travelLog[i].x}, y=${rover.travelLog[i].y}`);
}
*/
}
Any input/suggestion will be greatly appreciated. I can't seem to find the mistake and it is quite infuriating. However, thank you again and have a lovely and festive time!
You need one more closing brace } at the end of the moveBackward function. You closed the switch statement but not the function.
Happy Holidays!

Add pause key in a game javascript

I create little game but I have some trouble to put a pause key. It doesn't work. Can you see what is wrong and correct me? Thanks. I would like to know how to implement a pause key and a key for restart for not refresh the page for do it.
Link of the game
code:
//this is where the keybinding occurs
$(document).keydown(function(e){
if(!gameOver && !playerHit){
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(gameLoop, 1000 / 30);
gamePaused = false;
}
Keys down:
switch(e.keyCode){
case 75: //this is shoot (k)
//shoot missile here
var playerposx = $("#player").x();
var playerposy = $("#player").y();
var name = "playerMissle_"+Math.ceil(Math.random()*1000);
$("#playerMissileLayer").addSprite(name,{animation: missile["player"], posx: playerposx + 90, posy: playerposy + 14, width: 36,height: 10});
$("#"+name).addClass("playerMissiles")
break;
case 65: //this is left! (a)
$("#playerBooster").setAnimation();
break;
case 87: //this is up! (w)
$("#playerBoostUp").setAnimation(playerAnimation["up"]);
break;
case 68: //this is right (d)
$("#playerBooster").setAnimation(playerAnimation["booster"]);
break;
case 83: //this is down! (s)
$("#playerBoostDown").setAnimation(playerAnimation["down"]);
break;
Pause key P:
case 80: //pause (p)
pauseGame();
alert ("paused")
}
}
});
Key released:
//this is where the keybinding occurs
$(document).keyup(function(e){
if(!gameOver && !playerHit){
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(gameLoop, 1000 / 30);
gamePaused = false;
switch(e.keyCode){
case 65: //this is left! (a)
$("#playerBooster").setAnimation(playerAnimation["boost"]);
break;
case 87: //this is up! (w)
$("#playerBoostUp").setAnimation();
break;
case 68: //this is right (d)
$("#playerBooster").setAnimation(playerAnimation["boost"]);
break;
case 83: //this is down! (s)
$("#playerBoostDown").setAnimation();
break;
case 80: //pause (p)
pauseGame();
}
}
});
Pause function:
function Pause () {
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(gameLoop, 1000 / 30);
gamePaused = false;
}};
Try and check if the P key is registered at all (using alert or a console message).
Then
I would also suggest the following: do not set the actual gameloop interval (or call game functions) inside the keyUp / keyDown handlers. Place actual game code inside their own functions, for example:
bGamePaused = false;
// key handlers
$(document).keydown(function(e){
switch(e.keyCode){
case 80:
// check if the key is registered
console.log("p is pressed, pause the game!");
// toggle the paused status:
bGamePaused = !bGamePaused;
// tell gameQuery to pause or resume the game
(bGamePaused) ? pauseGame() : resumeGame();
break;
}
$(document).keyup(function(e){
switch(e.keyCode){
// do not check for pause here. you only need to check when the key is either pressed or released, or the function will get called twice.
}

JQuery while keydown

How can i make a movement of a element while the user is "keydown" and then if he make "keyup" to stop the animation(movement), this is my code by now
$(document).ready(function(){
function checkKey(e){
switch (e.keyCode) {
case 40:
//alert('down');
$('#cube').animate({top: "+=20px"})
break;
case 38:
//alert('up');
$('#cube').animate({top: "-=20px"})
break;
case 37:
//alert('left');
$('#cube').animate({left: "-=20px"})
break;
case 39:
//alert('right');
$('#cube').animate({left: "+=20px"})
break;
default:
alert('???');
}
}
if ($.browser.mozilla) {
$(document).keydown (checkKey);
} else {
$(document).keydown (checkKey);
}
})
i want to move the cube while the user press the key (down, left, up, right), not with every press, is possible?
You need a simple 2D engine that will setup a game loop.
Simple demo: http://jsfiddle.net/kzXek/
Source: https://github.com/superrob/simple-2D-javascript-engine/blob/master/simple2d.html
Is that you are looking for?
$(document).on("keyup", function() {
$("#cube").stop(true);
});
DEMO: http://jsfiddle.net/LjGRe/
you can just change the checkKey function, and add this to it :
function checkKey(e){
$(document).keyup(return);
switch (e.keyCode) {
case 40:
//alert('down');
$('#cube').animate({top: "+=20px"})
break;
case 38:
//alert('up');
$('#cube').animate({top: "-=20px"})
break;
case 37:
//alert('left');
$('#cube').animate({left: "-=20px"})
break;
case 39:
//alert('right');
$('#cube').animate({left: "+=20px"})
break;
default:
alert('???');
}
}
I think using a timer to handle the animation is better.
You just start the timer when a key is pressed and stop it when the key is released ..
Here is a simple solution that handles multiple keypresses (can move diagonally)
var direction = {top:0,left:0},
animator = null,
cube = $("#cube");
function animate(){
cube.css({
top: '+=' + direction.top,
left: '+=' + direction.left
});
}
function setProperties(keyCode, unset){
switch (keyCode) {
case 40:
direction.top = (unset)?0:2;
break;
case 38:
direction.top = (unset)?0:-2;
break;
case 37:
direction.left = (unset)?0:-2;
break;
case 39:
direction.left = (unset)?0:2;
break;
}
}
function setKey(e) {
setProperties(e.keyCode);
if (animator === null){
animator = setInterval(animate, 10);
}
}
function unsetKey(e){
setProperties(e.keyCode, true);
if (direction.top === 0 && direction.left === 0){
clearTimeout(animator);
animator = null;
}
}
$(document)
.on("keyup", unsetKey)
.on('keydown', setKey);
Demo at http://jsfiddle.net/gaby/Cu6nW/

JavaScript Keyboard Event Not Firing

For some very odd reason when you press keys in the order of forward, spacebar, and left. Left does not fire and returns spacebar instead. Any other combination of three keys works perfectly fine, but not that one. Any clues as to why?
var Ctrl = {
init: function() {
window.addEventListener('keydown', this.keyDown, true);
window.addEventListener('keyup', this.keyUp, true);
},
keyDown: function(event) {
console.log(event.keyCode);
switch(event.keyCode) {
case 37: // Left
Ctrl.left = true;
break;
case 39: // Right
Ctrl.right = true;
break;
case 38: // up
Ctrl.up = true;
break;
case 40: // down
Ctrl.down = true;
break;
case 32:
Ctrl.space = true;
break;
default:
break;
}
},
keyUp: function(event) {
switch(event.keyCode) {
case 37: // Left
Ctrl.left = false;
break;
case 39: // Right
Ctrl.right = false;
break;
case 38:
Ctrl.up = false;
break;
case 40:
Ctrl.down = false;
break;
case 32:
Ctrl.space = false;
break;
default:
break;
}
}
};
Maybe one of your keys is activating an unwanted default behavior. You can try to add event.preventDefault(); to your event bindings.
check the jsFiddle
It depends on model of your keyboard. Some keyboards doesn't work with some key combinations. It's normal.

Categories

Resources