Javascript function for moving div with arrow keys not working? - javascript

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.

Related

how to get multiple keyboard inputs in javaScript

I am trying to make a pong like game in html, but every time one player try to move the other movement will stop.
//javaScript
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115)
{
p1axis += 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 119)
{
p1axis -= 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 108)
{
p2axis += 2;
document.getElementById("p2").style.top = p2axis + "%";
}
if(x == 111)
{
p2axis -= 2;
document.getElementById("p2").style.top = p2axis + "%";
}
}
I expect that both players will be able to play freely.
instead only one can move at once.
You can create an array and add keys as they are pressed. You will have to remove them as the key is released. Also, I just used keydown with jQuery, you can also use keydown with JavaScript.
var bKeys = [];
$('body').keydown(function(e) {
if (bKeys.includes(e.which) === false) {
bKeys.push(e.which);
}
});
$('body').keyup(function(e) {
bKeys.pop(e.which);
});
setInterval(() => {
console.log(bKeys);
}, 15);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Remember to click in the body when you run the code
var k1 = false, k2 = false, k3 = false, k4 = false;
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = true;
}
if(x == 119 || x == 87)
{
k2 = true;
}
if(x == 108 || x == 76)
{
k3 = true;
}
if(x == 111 || x == 79)
{
k4 = true;
}
}
function remove(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = false;
}
if(x == 119 || x == 87)
{
k2 = false;
}
if(x == 108 || x == 76)
{
k3 = false;
}
if(x == 111 || x == 79)
{
k4 = false;
}
}
function move()
{
if(k1)
{
p1axis += 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k2)
{
p1axis -= 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k3)
{
p2axis += 1;
document.getElementById("p2").style.top = p2axis + "%";
}
if(k4)
{
p2axis -= 1;
document.getElementById("p2").style.top = p2axis + "%";
}
setTimeout(move, 20);
}

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!

Javascript +/+= Operator

I am having trouble with a basic movement engine I have made, where the Up key triggers a function making a small div go up, and the Down key doing the opposite. I am fairly sure it's to do with the += in the Down() function, and I have tested it with -=, which works fine, just I can't work out what might be clashing with the function.
At the bottom, I have put a comment to indicate where my problem is.
var interval = '';
var key = false;
var interval1 = '';
var key1 = false;
$(document).keydown(function(e) {
if(e.which === 38) {
if(key === false){
interval = setInterval(function(){Up()},20)
key = true;
}
}
if(e.which === 40) {
if(key1 === false){
interval1 = setInterval(function(){Down()},20)
key1 = true;
}
}
});
$(document).keyup(function(e) {
if(e.which === 38) {
clearInterval(interval)
key = false;
}
if(e.which === 40) {
clearInterval(interval1)
key1 = false;
}
});
document.getElementById('Jumper').style.top = '46%';
var Top = parseInt(document.getElementById('Jumper').style.top);
var Topp = parseInt(document.getElementById('Jumper').style.top);
function Up(){
if(Top > 0){
Top = parseInt(document.getElementById('Jumper').style.top);
Top -= 0.2;
document.getElementById('Jumper').style.top = Top+'%';
}
}
function Down(){
if(Topp > 0){
Topp = parseInt(document.getElementById('Jumper').style.top);
Topp += 0.2; //<--PROBLEM
document.getElementById('Jumper').style.top = Topp+'%';
}
}
#Jumper{
position: absolute;
top: 46%;
left: 48%;
height: 8%;
width: 4%;
background-color: red;
opacity: 1;
}
<div id='Jumper'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Can anyone please tell me how I can fix this?
Here is a fiddle of it: https://jsfiddle.net/Tobsta/2gnoq5hx/
You must use parseFloat(), because parseInt returns integer ::
Topp = parseFloat(document.getElementById('Jumper').style.top);
https://jsfiddle.net/2gnoq5hx/3/
It was this line that stuffed it all up:
Topp = parseInt(document.getElementById('Jumper').style.top);
Thanks Juhana for pointing that out.
Here's the working thing:
var interval = '';
var key = false;
var interval1 = '';
var key1 = false;
var interval2 = '';
var key2 = false;
var interval3 = '';
var key3 = false;
$(document).keydown(function(e) {
if(e.which === 38) {
if(key === false){
interval = setInterval(function(){Up()},20)
key = true;
}
}
if(e.which === 40) {
if(key1 === false){
interval1 = setInterval(function(){Down()},20)
key1 = true;
}
}
if(e.which === 37) {
if(key2 === false){
interval2 = setInterval(function(){Left()},20)
key2 = true;
}
}
if(e.which === 39) {
if(key3 === false){
interval3 = setInterval(function(){Right()},20)
key3 = true;
}
}
});
$(document).keyup(function(e) {
if(e.which === 38) {
clearInterval(interval)
key = false;
}
if(e.which === 40) {
clearInterval(interval1)
key1 = false;
}
if(e.which === 37) {
clearInterval(interval2)
key2 = false;
}
if(e.which === 39) {
clearInterval(interval3)
key3 = false;
}
});
document.getElementById('Jumper').style.top = '46%';
document.getElementById('Jumper').style.left = '48%';
var a = parseInt(document.getElementById('Jumper').style.top);
var b = parseInt(document.getElementById('Jumper').style.left);
function Up(){
if(a > 0){
a -= 1;
document.getElementById('Jumper').style.top = a+'%';
}
}
function Down(){
if(a < 92){
a += 1;
document.getElementById('Jumper').style.top = a+'%';
}
}
function Left(){
if(b > 0){
b -= 0.5;
document.getElementById('Jumper').style.left = b+'%';
}
}
function Right(){
if(b < 96){
b += 0.5;
document.getElementById('Jumper').style.left = b+'%';
}
}
#Jumper{
position: absolute;
top: 46%;
left: 48%;
height: 8%;
width: 4%;
background-color: red;
opacity: 1;
}
<div id='Jumper'></div>
Or the js fiddle
http://www.jsfiddle.net/Tobsta/2gnoq5hx/2

Unable to fetch the div style left value....

I have just started learning javascript and I was trying to move a div element using javascript. I was using the left and top property of style to move the div. The code is below.
html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
window.onload = function() {
divObj = document.getElementById('divObj');
window.onkeydown=function(e) {
var keycode;
keycode = e.keyCode;
speed = 1;
if(keycode == 37) {
divObj.style.left = (parseInt(divObj.style.left) - speed) + "px"; }
else if(keycode == 38)
divObj.style.top = (parseInt(divObj.style.top) - speed) + "px";
else if(keycode == 39)
divObj.style.left = (parseInt(divObj.style.left) + speed) + "px";
else if(keycode == 40)
divObj.style.top = (parseInt(divObj.style.top) + speed) - "px";
}
}
</script>
<style>
div.div1 { width : 200px;
height :50px;
background-color : #333;
position:absolute;
left:0px;
top:0px;
}
</style>
</head>
<body>
<div id = "divObj" class = "div1"></div>
</body>
</html>
The problem is that the 'divObj.style.left' is not returning any value and so the div cannot be moved using the up and down key.
If anyone knows how to get the values of style left property of the div, please let me know.
You need individual braces for all your else if statements
if(keycode == 37) {
divObj.style.left = (parseInt(divObj.style.left) - speed) + "px"; }
else if(keycode == 38){
divObj.style.top = (parseInt(divObj.style.top) - speed) + "px";}
else if(keycode == 39){
divObj.style.left = (parseInt(divObj.style.left) + speed) + "px"; }
else if(keycode == 40){
divObj.style.top = (parseInt(divObj.style.top) + speed) - "px";}
Try this
window.onload = function () {
divObj = document.getElementById('divObj');
window.onkeydown = function (e) {
var keycode;
keycode = e.keyCode;
speed = 1;
if (keycode == 37)
divObj.style.left =
((divObj.style.left == "" ? "0" : parseInt(divObj.style.left)) + speed) + "px";
else if (keycode == 38)
divObj.style.top =
((divObj.style.top == "" ? "0" : parseInt(divObj.style.top)) + speed) + "px";
else if (keycode == 39)
divObj.style.left = (
(divObj.style.left == "" ? "0" : parseInt(divObj.style.left)) + speed) + "px";
else if (keycode == 40)
divObj.style.top =
((divObj.style.top == "" ? "0" : parseInt(divObj.style.top)) + speed) + "px";
}
}
I made it this way
divObj = document.getElementById('divObj');
window.onkeydown=function(e) {
var keycode;
var lll = divObj.offsetLeft
var rrr = divObj.offsetTop
keycode = e.keyCode;
speed = 1;
if(keycode == 37) {
divObj.style.left = lll - speed+"px";}
else if(keycode == 38){
divObj.style.top = rrr - speed+"px";}
else if(keycode == 39){
divObj.style.left = lll + speed+"px";}
else if(keycode == 40){
divObj.style.top = rrr + speed+"px";}
}
jsfiddle

JS trigger keydown event

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/

Categories

Resources