Javascript move players with keys - javascript

I am trying to be able to control two players and make them move with a certain speed, I ain't getting any errors in the console and it writes out what it should be doing... But I see no action happening.
//control system
window.addEventListener('keydown', function (event) {
//left key
if (event.keyCode === 37) {
playerOne.x -= 1;
console.log("player 1 left");
}
//right key
else if (event.keyCode === 39) {
playerOne.x += 1;
console.log("player 1 right");
}
//up key
else if (event.keyCode === 38) {
playerOne.y -= 1;
console.log("player 1 up");
}
//down
else if (event.keyCode === 40) {
playerOne.y += 1;
console.log("player 1 down");
}
// bomb
else if (event.keyCode === 13) {
console.log("place bomb");
}
});
window.addEventListener('keydown', function (event) {
//left key
if (event.keyCode === 65) {
playerTwo.x -= 1;
console.log("player 2 left");
}
//right key
else if (event.keyCode === 68) {
playerTwo.x += 1;
console.log("player 2 right");
}
//up key
else if (event.keyCode === 87) {
playerTwo.y -= 1;
console.log("player 2 up");
}
//down
else if (event.keyCode === 83) {
playerTwo.y += 1;
console.log("player 2 down");
}
// bomb
else if (event.keyCode === 32) {
console.log("place bomb");
}
});
function movePlayers() {
"use strict";
if (keys.moveLeft) {
playerOne.x -= powerUps.speed;
if (playerOne.currentDirection != "left") {
playerOne.gotoAndPlay('left')
playerOne.currentDirection = "left";
}
}
if (keys.moveRight) {
playerOne.x += powerUps.speed;
if (playerOne.currentDirection != "right") {
playerOne.gotoAndPlay('right')
playerOne.currentDirection = "right";
}
}
if (keys.moveUp) {
playerOne.y -= powerUps.speed;
if (playerOne.currentDirection != "up") {
playerOne.gotoAndPlay('up')
playerOne.currentDirection = "up";
}
}
if (keys.moveDown) {
playerOne.y += powerUps.speed;
if (playerOne.currentDirection != "down") {
playerOne.gotoAndPlay('down')
playerOne.currentDirection = "down";
}
}
if (keys.moveLeft) {
playerTwo.x -= powerUps.speed;
if (playerTwo.currentDirection != "left") {
playerTwo.gotoAndPlay('left')
playerTwo.currentDirection = "left";
}
}
if (keys.moveRight) {
playerTwo.x += powerUps.speed;
if (playerTwo.currentDirection != "right") {
playerTwo.gotoAndPlay('right')
playerTwo.currentDirection = "right";
}
}
if (keys.moveUp) {
playerTwo.y -= powerUps.speed;
if (playerTwo.currentDirection != "up") {
playerTwo.gotoAndPlay('up')
playerTwo.currentDirection = "up";
}
}
if (keys.moveDown) {
playerTwo.y += powerUps.speed;
if (playerTwo.currentDirection != "down") {
playerTwo.gotoAndPlay('down')
playerTwo.currentDirection = "down";
}
}
}

That´s only an Tipp not an answer - but the place in comments is not enough.
I thinks that´s not an good way with your "if" construction, a sample for an easier way:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table key´s</title>
<style>
td{width:10px;height:10px;background:#ddd;}
tr:nth-child(5) td:nth-child(5){background:#f00;}
</style>
</head>
<body>
<div id="tableContainer">
</div>
<script>
var row=col=5,max=10;
tableContainer.innerHTML = '<table>'+('<tr>'+'<td>'.repeat(max)).repeat(max)+'</table>';
window.addEventListener("keyup", function(e){
var colDiff, rowDiff;
var keyMap = new Map([[37,[-1,0]],[38,[0,-1]],[39,[1,0]],[40,[0,1]]]);
if (keyMap.has(e.keyCode)){
document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#ddd';
[colDiff,rowDiff]=keyMap.get(e.keyCode);
row+=rowDiff;
col+=colDiff;
row = (row>max) ? max : (row < 1) ? 1 : row;
col = (col>max) ? max : (col < 1) ? 1 : col;
document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#f00';
}
})
</script>
</body>
</html>

Related

What's the best way to restrict movement for the camera to a certain location in THREE js?

I'm making a game that includes gravity and I need to make it so when you hit a wall or something than you can't move. I was thinking something along the lines of just stopping the forward movement but then you can just turn around and go into it backwards. No such luck so far.
Here's my movement code:
document.onkeydown = function(e) {
// e.preventDefault()
if(e.keyCode == 87) {
player.movement.w = true
}
if(e.keyCode == 65) {
player.movement.a = true
}
if(e.keyCode == 83) {
player.movement.s = true
}
if(e.keyCode == 68) {
player.movement.d = true
}
if(e.keyCode == 69) {
player.movement.e = true
}
if(e.keyCode == 81) {
player.movement.q = true
}
}
document.onkeyup = function(e) {
if(e.keyCode == 87) {
player.movement.w = false
}
if(e.keyCode == 65) {
player.movement.a = false
}
if(e.keyCode == 83) {
player.movement.s = false
}
if(e.keyCode == 68) {
player.movement.d = false
}
if(e.keyCode == 69) {
player.movement.e = false
}
if(e.keyCode == 81) {
player.movement.q = false
}
}
function loop() {
requestAnimationFrame(loop)
if(player.look.locked == true) {
if(player.movement.w == true) {
playerObj.translateZ(player.movement.speed / 100)
}
if(player.movement.a == true) {
playerObj.translateX(player.movement.speed / 100)
}
if(player.movement.s == true) {
playerObj.translateZ(player.movement.speed / 100 * -1)
}
if(player.movement.d == true) {
playerObj.translateX(player.movement.speed / 100 * -1)
}
if(player.movement.e == true) {
playerObj.translateY(player.movement.speed / 100 * -1)
}
if(player.movement.q == true) {
playerObj.translateY(player.movement.speed / 50)
}
}
}
loop()
(I know event.keyCode is depreciated)

Character will not jump after touching in JS

I am programming collision detection in JS for a platformer. For some reason, when my character touches the ground on the top, it won't jump again. Here's my code:
if (isCollideY(platforms[i].getBoundingClientRect(), document.getElementById('spriteNotReal').getBoundingClientRect()) == true) {
if (falling == true && (jumping == false)) {
moveY = platforms[i].getBoundingClientRect().y + 3;
momentumY = 0;
onSolidGround = true;
}
}
if (event.code == 'KeyW' && (moveY <= 300)) {
moveY += 1;
move (moveX, moveY);
momentumY = momentumY + 20;
onSolidGround = false;
falling = false;
jumping = true;
}
else if (onSolidGround == false) {
if (momentumY < 0) {
falling = true;
}
else if (momentumY > 0) {
jumping = true;
}
else {
jumping = false;
}
moveX += momentumX / 3 + 1;
document.getElementById("spriteNotReal").src = "jumpmain.gif";
}
My problem was somewhat stupid. After checking the input code, I realized that the jump wasn't happening because it would only jump while on the "platform" I set up to test, not while it was actually on a platform. Here's the improved code:
if (event.code == 'KeyW' && (onSolidGround == true)) {
moveY += 1;
move (moveX, moveY);
momentumY = momentumY + 20;
onSolidGround = false;
falling = false;
jumping = true;
}

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);
}

How to move an element in javascript automatically with while loop?

I am making a Snake game so I'm trying to move my snake. It is moving with keys but it should move automatically on the screen. I tried doing that with while loops like in the code below but because of break; I have to press a key every time I want it to move. How can I make it move automatically? I tried removing break; an using an if statement but I didn't succeed.
Any other solutions or something else?
I'm new to programming so any advices would be helpful.
var main = function() {
var i = 0;
var j = 0;
$(document).keyup(function(event) {
var e = event.which;
while(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
while(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
while(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
while(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}
//Which key is preesed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}
});
};
$(document).ready(main);
I think you just have to organize a little bit your code.
First. You must put your code inside a function. You really don't need a while. You can use a simple if.
function move(i) {
if(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
if(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
if(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
if(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}
}
Now you have to change the event, using keydown instead of keyup
function main() {
var interval;
$(document).keydown(function(event) {
if(interval) clearInterval(interval); // Clear the previous interval
var e = event.which;
var i;
//Which key is pressed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}
interval = setInterval(function() {
move(i)
},1000); // repeat every 1 second
});
}
$(document).ready(main);

My keydown event is runs too many times if i click the button

$(document).keydown(function(e) {
if(e.keyCode == 37) { // left
e.preventDefault();
$("#news_container_inner").animate({
// zuun
left: (int_px($("#news_container_inner").css("left")) + 945) > 0 ? MAX_LENGTH : "+=945"
});
$('#dragBar').animate({
left: (int_px($("#dragBar").css("left")) - dragBar_road) < 0 ? MAX_LENGTH_Drag+1 : "-="+dragBar_road
});
console.log('left');
}
else if(e.keyCode == 39) { // right
e.preventDefault();
$("#news_container_inner").animate({
// baruun
left: (int_px($("#news_container_inner").css("left")) - 945) < MAX_LENGTH ? 0 : "-=945"
});
$('#dragBar').animate({
left: (int_px($("#dragBar").css("left")) + dragBar_road) > MAX_LENGTH_Drag+1 ? 1 : "+="+dragBar_road
});
console.log('right');
}
});
Here is my code. The problem is if i click right arrow button for 1 second this event runs 35 times. I need to bind it 3 or 4 times if i click for 1 second.
Sorry for bad english.
Please help me.
You could work with a counter if you just want to fire it e.g. 4 times:
var counter = 0;
$(document).on('keydown', function(e) {
e.preventDefault();
counter++;
if(counter > 4) {
return;
}
if(e.keyCode == 37) {
console.log('left');
} else if(e.keyCode == 39) {
console.log('right');
}
}).on('keyup', function(e) {
counter = 0;
});
DEMO
EDIT
If you want to limit the number of events per second you can use setInterval:
var counter = 0,
intervalInited = false;
function initInterval() {
intervalInited = true;
setInterval(function(){
if(counter > 4) {
counter = 0;
}
}, 1000);
}
$(document).on('keydown', function(e) {
e.preventDefault();
counter++;
if(counter > 4) {
if(!intervalInited) {
initInterval();
}
return;
}
if(e.keyCode == 37) {
console.log('left');
} else if(e.keyCode == 39) {
console.log('right');
}
}).on('keyup', function(e) {
counter = 0;
});
DEMO

Categories

Resources