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/
Related
function control()
{
var ship = document.getElementById("ship");
document.onkeydown = function(e) {
switch (e.keyCode) {
case 38:
ship.style.top += "5%";
break;
case 40:
ship.style.top -= "5%";
break;
default:
break;
}
}
}
setInterval(control,1000);
This code is not working.
The object I'm trying to move is not moving when I'm pressing the Up & Down Arrow Key.
You can't do
ship.style.top += "5%";
because ship.style.top value is not a number but a string. the += opérator is concatening strings here.
You should do something like that:
const ship = document.getElementById("ship");
document.onkeydown = function (e) {
let winHeigth = window.innerHeight;
let top = ship.style.top;
switch (e.code) {
case "ArrowUp":
ship.style.top = (Number(top.substring(0, top.length - 2)) - (winHeigth / 20)) + "px";
break;
case "ArrowDown":
ship.style.top = (Number(top.substring(0, top.length - 2)) + (winHeigth / 20)) + "px";
break;
default:
break;
}
}
The position attribute of the "ship" must be like "relative".
By the way, e.keyCode is deprecated, you can use e.code instead ^^
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/
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.
}
E.g. I have the following script
<script>
document.onkeydown = function(evt){
evt = evt || window.event;
switch (evt.keyCode){
case 67:
createNewFile();
break;
case 82:
goToRecords();
break;
case 84:
goToToday();
break;
case 36:
goToMsHome();
break;
case 27:
escToCloseOptions();
break;
case 83:
summary();
break;
case 73:
insertRecord();
break;
}
};
</script>
When I press
shift + keycode
to call a function specified, I am just new to JavaScript and I code JavaScript based on other languages I know
Thanks and Regards
Check .shiftKey which returns a boolean indicating if the key is pressed. Placing this conditional around your switch will prevent any events from occurring unless the key is pressed in combination with shift.
document.onkeydown = function(evt){
evt = evt || window.event;
if(evt.shiftKey){
switch (evt.keyCode){
case 67:
createNewFile();
break;
case 82:
goToRecords();
break;
case 84:
goToToday();
break;
case 36:
goToMsHome();
break;
case 27:
escToCloseOptions();
break;
case 83:
summary();
break;
case 73:
insertRecord();
break;
}
}
};
You can detect the shift key separately. e.g. if you want to call createNewFile with the shift key down:
if(evt.shiftKey && evt.keyCode == 67) {
createNewFile();
}
In your code, you could do something like:
evt = evt || window.event;
switch (evt.keyCode){
case 67:
if (evt.shiftkey) {
// Do something special for shift mode.
} else {
createNewFile();
}
break;
...
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.