JS trigger keydown event - javascript

I'm slightly confused why this code isn't working:
$(document).keydown(function(e){
if (e.keyCode == 39) {
//RIGHT
document.getElementById('col_detector_right').innerHTML="";
col_jack('right');
if(document.getElementById('col_detector_right').innerHTML!=""){
}
else{
var left = document.getElementById('jack').style.left;
var current_left = parseFloat(left);
var new_left = current_left + 400;
document.getElementById('jack').style.left = new_left+'px';
}
right = true;
return false;
}
if (e.keyCode == 37) {
//LEFT
document.getElementById('col_detector_right').innerHTML="";
col_jack('right');
if(document.getElementById('col_detector_right').innerHTML!=""){
}
else{
var left = document.getElementById('jack').style.left;
var current_left = parseFloat(left);
var new_left = current_left - 4;
document.getElementById('jack').style.left = new_left+'px';
}
right = false;
return false;
}
if (e.keyCode == 38) {
//UP
return false;
}
if (e.keyCode == 40) {
//DOWN
return false;
}
if (e.keyCode == 32) {
//SPACE
if(right==true){
var top = document.getElementById('jack').style.top;
var current_top = parseFloat(top);
var new_top = current_top -40;
document.getElementById('jack').style.top = new_top+'px';
var left = document.getElementById('jack').style.left;
var current_left = parseFloat(left);
var new_left = current_left + 20;
document.getElementById('jack').style.left = new_left+'px';
right=false;
var press = $.Event('keydown');
press.which = 39;
$(document).trigger(press);
}
else{
var top = document.getElementById('jack').style.top;
var current_top = parseFloat(top);
var new_top = current_top -40;
document.getElementById('jack').style.top = new_top+'px';
}
return false;
}
});
specificly this bit, is not working:
var press = $.Event('keydown');
press.which = 39;
$(document).trigger(press);
why? the idea is that it should trigger the right arrow key but it's not? Nothing is happening, it's either not triggering it or it's not checking the keydown event properly? I don't know which or is it something else?

You need to pass an object of properties to the jQuery Event object, like so:
// Create a new jQuery.Event object with specified event properties.
var e = jQuery.Event("keydown", { keyCode: 64 });
// trigger an artificial keydown event with keyCode 64
jQuery("body").trigger( e );
Read the API docs for $.Event - http://api.jquery.com/category/events/event-object/

Related

Trouble with adding gravity to 2d platformer

I am trying to make a 2D platforming game and I am missing an essential part of it, gravity.
I have tried everything from look at questions on this website to looking at online tutorials and you-tube videos.
I really need help with getting gravity into this game as I am out of ideas.
As I said I have already tried looking at multiple tutorials and videos, including this one:
http://www.somethinghitme.com/2013/01/09/creating-a-canvas-platformer-tutorial-part-one/
but this one uses shapes created in canvas rather than images.
I already know that you have to use a velocity function as well as variable for the gravity. Then you have to put this all inside the key handler function so that it can get executed.
//spaceman variables
var sx = canvasWidth / 2; // start the spaceman in the centre
var sy = canvasHeight / 2;
var sdx = 0; // set initial speed to 0
var sdy = 0;
var sspeed = 3; // create a variable for speed
var gravity = 0.2;
var svX = 0;
var svY = (Math.random() * -10) - 5;
//set variables to use for key presses
//these are Boolean variables
//they can only be true or false
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
spaceman2Ready = true;
spacemanReady = false;
leftPressed = true;
} else if (e.keyCode == 38) {
upPressed = true;
} else if (e.keyCode == 40) {
downPressed = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
sdx--;
} else if (e.keyCode == 37) {
spaceman2Ready = false;
spacemanReady = true;
leftPressed = false;
sdx--;
} else if (e.keyCode == 38) {
upPressed = false;
sdx--;
} else if (e.keyCode == 40) {
downPressed = false;
sdx--;
}
}
// add something to "listen" for an event
//an event is keypress, mouse movement, mouse click etc.
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (rightPressed == true) {
sdx = sspeed;
} else if (leftPressed == true) {
sdx = -sspeed;
} else if (upPressed == true) {
sdy = -sspeed;
} else if (downPressed == true) {
sdy = sspeed
}
if (rightPressed == false && leftPressed == false && upPressed == false && downPressed == false) {
sdx = 0;
sdy = 0;
}
sx = sx + sdx;
sy = sy + sdy;
}
if (spacemanReady) {
ctx.drawImage(spacemanImage, sx, sy);
if (spaceman2Ready) {
ctx.drawImage(spaceman2Image, sx, sy);
}
// basically the setTimeout part, but this time its requesting the function that we made at the top
requestAnimationFrame(draw);
}
// this is to get the loop for the animation to start going
window.addEventListener("load",
function() {
draw();
});
< /script>
</body >
</html>/
You should be using gravity to update your position every frame (in the draw function). This would look like:
if(sy > 0){
sdy += gravity
}
I have created a codepen with your game with gravity. I hope this helps!

Snake in JavaScript: I can't get my snakes tail longer

I made a snake game that works almost completely. I have one snake head, and an array which contains the head and all of the tails. When the snake eats a food, the food moves location, but my tail isn't getting bigger when I eat the food. I don't have an IMMENSE understanding of arrays, perhaps I'm doing it wrong?
Here is the code:
setSize(400, 400);
var background = new Rectangle(getWidth(), getHeight());
background.setPosition(0, 0);
background.setColor(Color.black);
add(background);
// ------------------------------------------------
var gameTime = 0;
var snakeX = (Randomizer.nextInt(0, 19)) * 20;
var snakeY = (Randomizer.nextInt(0, 19)) * 20;
var foodX;
var foodY;
var snakeFood = new Rectangle(20, 20);
snakeFood.setColor(Color.red);
var food_eaten = 0;
var snakeSpeed = 20;
var keyLeft = false;
var keyRight = false;
var keyUp = false;
var keyDown = false;
var snake_size = 10;
var snakeHead = new Rectangle(20, 20);
snakeHead.setColor(Color.green);
var snakes = [snakeHead];
// ------------------------------------------------
function start(){
setup();
keyDownMethod(checkKey);
setTimer(counter, 250);
}
function counter(){
gameTime += 0.25;
updateSnake();
}
function setup(){
foodX = (Randomizer.nextInt(0, 19)) * 20;
foodY = (Randomizer.nextInt(0, 19)) * 20;
snakeHead.setPosition(snakeX, snakeY);
add(snakeHead);
snakeFood.setPosition(foodX, foodY);
add(snakeFood);
}
function checkKey(e){
if(e.keyCode == Keyboard.LEFT){
keyRight = false;
keyUp = false;
keyDown = false;
keyLeft = true;
}else if(e.keyCode == Keyboard.RIGHT){
keyLeft = false;
keyUp = false;
keyDown = false;
keyRight = true;
}else if(e.keyCode == Keyboard.UP){
keyRight = false;
keyLeft = false;
keyDown = false;
keyUp = true;
}else if(e.keyCode == Keyboard.DOWN){
keyRight = false;
keyLeft = false;
keyUp = false;
keyDown = true;
}
}
function updateSnake(){
if(foodX == snakeX && foodY == snakeY){
eat();
}
var dirX = 0;
var dirY = 0;
if(keyLeft == true){
dirX = -(snakeSpeed);
dirY = 0;
}else if(keyRight == true){
dirX = snakeSpeed;
dirY = 0;
}else if(keyUp == true){
dirY = -(snakeSpeed);
dirX = 0;
}else if(keyDown == true){
dirY = snakeSpeed;
dirX = 0;
}
// moving the snake head
snakeHead.setPosition(snakeX + dirX, snakeY + dirY);
snakeX += dirX;
snakeY += dirY;
// moving the snake body
if(snakes.length > 1){
for(var i = 0; i < snakes.length; i++){
var curr_body = snakes[i];
curr_body.setPosition(snakeX + dirX, snakeY + dirY);
}
}
}
function eat(){
foodX = (Randomizer.nextInt(0, 19)) * 20;
foodY = (Randomizer.nextInt(0, 19)) * 20;
var tail = new Snake(snakeX, snakeY);
snakeFood.setPosition(foodX, foodY);
}
function Snake(x, y){
var snakeBody = new Rectangle(20, 20);
if(keyLeft == true){
snakeBody.setPosition(x + snake_size, y);
}if(keyRight == true){
snakeBody.setPosition(x - snake_size, y);
}if(keyUp == true){
snakeBody.setPosition(x, y + snake_size);
}if(keyDown == true){
snakeBody.setPosition(x, y - snake_size);
}
snakeBody.setColor(Color.green);
snakes.push(snakeBody);
add(snakeBody);
}
In your eat() function, you assign a new Snake object to a var tail, but then do nothing with it. I think you need to add it to your snakes array (which I assume represents the entire snake?)

requestAnimationFrame not working as intended Javascript

I'm making a game in which a player character moves left and right.
Since simply using an onKeyDown eventListener had my character move in a choppy fashion, and with a slight delay, I tried using requestAnimationFrame to call the movement function as often as possible, as suggested by another answer(How can I move my JS objects smoothly using keyboard input?)
however, that has changed nothing.
Here is my Javascript Code
var NodoCampo = document.getElementById("campo");
var NodoGiocatore = null;
var Left = false;
var Right = false;
var FRAMERATE = 20;
//cache giocatore
var LARG_GIOCATORE = 30;
var ALT_GIOCATORE = 30;
var X_GIOCATORE = 300;
var Y_GIOCATORE = 1100;
var VEL_GIOCATORE = 10;
function mostra_giocatore() {
if (NodoGiocatore === null) {
NodoGiocatore = document.createElement('div');
NodoGiocatore.setAttribute ('id', 'player');
NodoCampo.appendChild (NodoGiocatore);
}
NodoGiocatore.style.marginLeft = (X_GIOCATORE - LARG_GIOCATORE) + 'px';
NodoGiocatore.style.marginTop = (Y_GIOCATORE - ALT_GIOCATORE) + 'px';
}
function muovi() {
if (Left) {
X_GIOCATORE = X_GIOCATORE - VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
else if (Right) {
X_GIOCATORE = X_GIOCATORE + VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
}
function stop() {
Left = false;
Right = false;
}
function interfaccia(e) {
//freccia sinstra
if (e.keyCode === 37) {
X_GIOCATORE = X_GIOCATORE - VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
//freccia destra
else if (e.keyCode === 39) {
X_GIOCATORE = X_GIOCATORE + VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
}
function inizia() {
mostra_giocatore();
requestAnimationFrame(muovi);
}
window.document.onkeypress = interfaccia;
window.document.onkeyup = stop;
Your choppy movement is likely a result of the amount you are moving the player on each frame with VEL_GIOCATORE. Try reducing this amount to observe smoother movement.
The delay you are experiencing is likely due to your operating system or browsers individual settings on how key presses should repeat. You can work around this by implementing your own key tracking -- it looks like you've started to experiment with this. Track the state of your left and right keys by updating a boolean value in onkeydown and onkeyup event listeners.
var keys = {
left: false,
right: false
};
window.document.onkeydown = function (e) {
if (e.keyCode === 37) {
keys.left = true;
} else if (e.keyCode === 39) {
keys.right = true;
}
window.document.onkeyup = function (e) {
if (e.keyCode === 37) {
keys.left = false;
} else if (e.keyCode === 39) {
keys.right = false;
}
Then, in your muovi function, check the state of these variables to determine if you should update the position of the player.

Javascript function for moving div with arrow keys not working?

I've been trying to move a div around a page just using the arrows keys on my keyboard. It seems not to be working. I had it working before but for some reason it is no longer working. Could you let me know what you think the issue is? I have a feeling it has something to do with window.onkeydown and onkeyup.
Thank you for any help in advance.
CSS --
#log {
position:absolute;
width: 50px;
height: 50px;
border: 2px solid black;
background-color: white;
color: black;
font-size: 20px;
left: 20px;
}
HTML---
<div id="log"></div>
JavaScript --
var Keys = {
up: false,
down: false,
left: false,
right: false
};
var hero = {
x: 0,
y: 0
};
var log = document.getElementById("log");
window.onkeydown = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = true;
if(kc === 38) Keys.up = true;
if(kc === 39) Keys.right = true;
if(kc === 40) Keys.down = true;
};
window.onkeyup = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = false;
if(kc === 38) Keys.up = false;
if(kc === 39) Keys.right = false;
if(kc === 40) Keys.down = false;
};
function main() {
move();
};
function move(){
if(Keys.up){
hero.y -= 10;
var p = hero.y;
var t = p + 10;
log.style.top = p + "px";
log.style.bottom = t + "px";
//color();
}
if(Keys.down){
hero.y += 10;
var g = hero.y;
var q = g - 10;
log.style.bottom = g + "px";
log.style.top = q + "px";
//color();
}
if(Keys.left) {
hero.x -= 10;
var z = hero.x;
var q = z + 10;
log.style.left = z + "px";
log.style.right = q + "px";
//color();
}
if(Keys.right){
hero.x += 10;
var z = hero.x;
var q = z - 10;
log.style.right = z + "px";
log.style.left = q + "px";
// color();
}
}
setInterval(main, 50);
If you're open to using jQuery this might help you out.
$(document).ready(function() {
var hero = $("#log");
var speed = 1;
var direction = {
left: false,
up: false,
right: false,
down: false
};
$(document).on('keydown', function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) direction.left = true;
if (kc === 38) direction.up = true;
if (kc === 39) direction.right = true;
if (kc === 40) direction.down = true;
});
$(document).on('keyup', function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) direction.left = false;
if (kc === 38) direction.up = false;
if (kc === 39) direction.right = false;
if (kc === 40) direction.down = false;
});
function move() {
if (direction.left) hero.css("left", (hero.position().left - speed) + "px");
if (direction.up) hero.css("top", (hero.position().top - speed) + "px");
if (direction.right) hero.css("left", (hero.position().left + speed) + "px");
if (direction.down) hero.css("top", (hero.position().top + speed) + "px");
}
setInterval(move, 1);
});
Here's a Fiddle to demonstrate the result. Feel free to customize it to your needs.
UPDATE
And here's another Fiddle to accept multiple buttons pressed at the same time.

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>

Categories

Resources