When I put engine.map.ctx.translate(engine.moveX, engine.moveY); just like that it works perfectly, but when I try to invoke this function on key trigger it gives me nothing.
I'm checking with alert if key triggers works and they do, however engine.map.ctx.translate(engine.moveX, engine.moveY); isn't working inside switch statement.
var engine = {}
engine.moveX = 0;
engine.moveY = 0;
engine.map = {}
engine.map.canvas = document.getElementById('canvas');
engine.map.ctx = engine.map.canvas.getContext('2d');
document.onkeydown = function(evt) {
evt = evt || window.event;
switch(evt.keyCode){
case 37:
engine.moveX -= 15;
engine.map.ctx.translate(engine.moveX, engine.moveY);
alert('left');
break;
case 38:
engine.moveY -= 15;
engine.map.ctx.translate(engine.moveX, engine.moveY);
alert('up');
break;
case 39:
engine.moveX += 15;
engine.map.ctx.translate(engine.moveX, engine.moveY);
alert('right');
break;
case 40:
engine.moveY += 15;
engine.map.ctx.translate(engine.moveX, engine.moveY);
alert('down');
break;
}
};
The ctx.translate command is not designed to redraw anything
It only repositions the canvas for subsequent draws.
So you now need to also redraw your object.
Related
Every time I press one of these keys, it just moves further and further.
function update() {
window.addEventListener('keyup', (e) => {
switch (e.key) {
case 'w':
myY = myY + 1;
break
case 'a':
myX = myX - 1;
break
case 's':
myY = myY - 1;
break
case 'd':
myX = myX + 1;
break
}
}
})
To achieve a smooth movement, you need:
a tick loop
listening both on keydown and keyup events
Given the presence of the update() function, I think you already have a tick loop.
Note that the addEventListener() should only be called during the setup phase.
Here's an example:
let speedX = 0
let speedY = 0
function setup() {
window.addEventListener('keydown', (e) => {
switch (e.key) {
case 'w':
speedY += 1;
break
case 'a':
speedX -= 1;
break
case 's':
speedY -= 1;
break
case 'd':
speedX += 1;
break
}
}
window.addEventListener('keyup', (e) => {
switch (e.key) {
case 'w':
speedY -= 1;
break
case 'a':
speedX += 1;
break
case 's':
speedY += 1;
break
case 'd':
speedX -= 1;
break
}
}
}
function update() {
myX += speedX;
myY += speedY;
}
If you do not have a tick loop, here's one way to make one with requestAnimationFrame:
function loop() {
requestAnimationFrame(loop);
update();
}
setup();
loop();
Is there a way to call a function on the event of a key press.
My goal is to make a movable block and I was wondering if you could call the function to move a <div> block around. I also have an issue with making the character visible so it would be helpful to help me with that!
JavaScript
//variables
var player = document.getElementById('player');
var character = {
left: player.style.left + 1,
right: player.style.right + 1,
top: player.style.top + 1,
bottom: player.style.bottom + 1,
body: document.createElement('div'),
}
//functions
function running() {
console.log("Running");
console.log("Program running");
document.appendChild('div');
}
function loop() {
running();
}
function moveRight() {
character.style.position = absolute;
character.style.top = top + "px";
character.style.right = right + 2 + "px";
}
function moveLeft() {
character.style.position = absolute;
character.style.top = top + "px";
character.style.left = left + 2 + "px";
}
function moveup() {
character.style.position = absolute;
character.style.top = top + "px";
character.style.right = right + 2 + "px";
}
//functions called
loop();
HTML
<!DOCTYPE html>
<html>
<head>
<title>RPG</title>
</head>
<body>
<div id="allCode">
<script type="text/javascript" src="index.js"></script>
<style type="text/css" src="style.css"></style>
</div>
<div id="player"></div>
</body>
</html>
There are a lot of examples on how to deal with key handling events in javascript, this should get you started :
document.addEventListener('keydown', function(event) {
switch (event.keyCode) {
case 37:
//left function
break;
case 38:
//Up function
break;
case 39:
//Right function
break;
}
});
Edit: The .keyCode, .which, .charCode are deprecated properties:
so you should use event.key
for example:
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
switch (event.key) {
case "Up": // IE/Edge specific value
case "ArrowUp":
//Up function
break;
case "Left": // IE/Edge specific
case "ArrowLeft":
//left function
break;
case "Right": // IE/Edge specific
case "ArrowRight":
//Right function
break;
default:
return; // No key event
}
event.preventDefault(); // Avoid key handling twice
}, true);
Maybe this can lead you in the right direction. It's a link to move an object using arrow keys.
https://www.includehelp.com/code-snippets/move-object-with-arrow-keys-using-javascript-function.aspx
I want to make a div able to move with arrow keys in 4 direction with multikey support(e.x. moving to top left) onkeypress. When i click some of the arrows i expect moving to that direction until i put my finger up from that button. Although the move is just once which i don't understand why is happening.
function place(id,x_pos, y_pos) {
var element = document.getElementById(id);
element.style.position = "absolute";
element.style.left = x_pos+'px';
element.style.top = y_pos+'px';
}
setInterval(update,1);
function update(){
document.addEventListener('keydown', keyPress);
}
function keyPress(e) {
var x = e.keyCode;
switch (x) {
case 37:
place('move', move.style.left-10, move.style.top);
break;
case 39:
place('move', move.style.left+10, move.style.top);
break;
case 38:
place('move', move.style.left, move.style.top-10);
break;
case 40:
place('move', move.style.left, move.style.top+10);
break;
}
// console.log(x);
}
*{
margin:0;
padding:0;
}
div#move{
background-color:yellow;
width:5vw;
height:5vw;
}
<div id='move'></div>
The problem with your code is that element.style.left give result as 10px and when you add 10 on 10px it will be a string like 10px10 which will make the property value incorrect.Since the first time the property is not set so first assignment id working fine. You need to get the left and right in numerical.
You also do not need to bind the update function with document with setInterval. Once is enough.
Check the code below
function place(id,x_pos, y_pos) {
var element = document.getElementById(id);
element.style.position = "absolute";
element.style.left = x_pos+'px';
element.style.top = y_pos+'px';
}
function update(){
document.addEventListener('keydown', keyPress);
}
function keyPress(e) {
var x = e.keyCode;
var move = document.getElementById("move").getBoundingClientRect();
var left = parseInt(move.left,10);
var top = parseInt(move.top,10)
switch (x) {
case 37:
place('move', left -10, top);
break;
case 39:
place('move', left+10, top);
break;
case 38:
place('move', left, top-10);
break;
case 40:
place('move', left, top+10);
break;
}
// console.log(x);
}
update();
*{
margin:0;
padding:0;
}
div#move{
background-color:yellow;
width:5vw;
height:5vw;
}
<div id='move'></div>
const move=document.getElementById('move');
var moveLeft = 0;
function direction(e){
if(e.keyCode==39){
moveLeft +=2;
move.style.left = moveLeft + 'px';
if(moveLeft>=600){
moveLeft -=2;
}
}
if(e.keyCode==37){
moveLeft -=2;
move.style.left = moveLeft + 'px';
}
if(e.keyCode==38){
moveLeft -=2;
move.style.top = moveLeft + 'px';
if(moveLeft>=600){
moveLeft +=2;
}
}
if(e.keyCode==40){
moveLeft +=2;
move.style.top = moveLeft + 'px';
}
}
document.onkeydown = direction;
#move{
position: absolute;
height: 50px;
width: 50px;
background-color: yellow
}
<div id="move"></div>
You don't need setInterval. Just register your listener, and it will handle every keypress.
document.addEventListener('keydown', keyPress);
function keyPress(e) {
var x = e.keyCode;
switch (x) {
case 37:
place('move', move.style.left-10, move.style.top);
break;
case 39:
place('move', move.style.left+10, move.style.top);
break;
case 38:
place('move', move.style.left, move.style.top-10);
break;
case 40:
place('move', move.style.left, move.style.top+10);
break;
}
// console.log(x);
}
How can I make the window scroll at a slower rate (horizontally and vertically) when triggered with the arrow keys? I've looked at some parallax demos, but they don't really do what I need. They mostly focus on background images, whereas I want my entire window and/or html body to slow down.
thanks!
Try to fiddle with this code:
addEventListener('keydown', function(e){
move = false;
x = false;
y = false;
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
switch(keycode){
case 37:
move = true;
x = 'negative';
break;
case 38:
move = true;
y = 'negative'
break;
case 39:
move = true;
x = 'positive'
break;
case 40:
move = true;
y = 'positive'
break;
}
if(move){
animation.move(x,y);
}
return false;
})
In Javascript, how do I tell if a user is pressing two keys at the same time?
For example, I have drawn a circle in the middle of the screen. I want to move it up while the user holds down the up arrow and right while the user holds down the right arrow. That part works easy. If user holds both the up and right arrows, I want to move the circle diagonally, up and to the right.
It doesn't look like this possible with basic Javascript event handling, but surely someone has figured out a work around/hack/improvement.
Here is what you need to do conceptually (I guess this is called pseudo code):
Start with something like this:
var PIXEL_DELTA = 10; // Distance to move in pixels
var leftPressed = 0,
upPressed = 0,
downPressed = 0,
rightPressed = 0;
Then on every keydown event, test if it the key pressed is left, up, etc and turn its variable from 0 to PIXEL_DELTA.
On every keyup event, run the same test and turn the correct variable back to 0.
Then, in your moving code (real code): (This code adapted from Crescent Fresh's awesome example):
function move() {
var dot = document.getElementById('dot'),
deltaX = rightPressed - leftPressed,
deltaY = downPressed - upPressed;
if(deltaX) {
dot.style.left = (parseInt(dot.style.left, 10) || 0) + deltaX + 'px';
}
if (deltaY) {
dot.style.top = (parseInt(dot.style.top, 10) || 0) + deltaY + 'px';
}
}
The browser will (should) fire a separate keydown/keyup event for each key, even if they are "simultaneously" pressed.
Working Example
Crescent Fresh put together a full example on JSBin. Be sure to visit the editable version as well to play with the code.
Javascript has onkeydown, and onkeyup events. You can simple fiddle a bit onkeydown for left arrow, and fiddle another bit for the up arrow. On keyup, fiddle the respective bit back.
var leftPressed,
upPressed,
rightPressed,
downPressed;
var milli = 100;
window.addEventListener('onkeydown', function(e) {
switch(e.keycode) {
case 37: //left
leftPressed = true;
case 38: //up
upPressed = true;
case 39: //right
rightPressed = true;
case 40: //down
downPressed = true;
default:
break;
}
});
window.addEventListener('onkeyup', function(e) {
switch(e.keycode) {
case 37: //left
leftPressed = false;
case 38: //up
upPressed = false;
case 39: //right
rightPressed = false;
case 40: //down
downPressed = false;
default:
break;
}
});
function moveCircle() {
if(leftPressed && !rightPressed) {
// move left
}
if(rightPressed && !leftPressed) {
// move right
}
if(upPressed && !downPressed) {
// move up
}
if(downPressed && !upPressed) {
// move down
}
}
setInterval(moveCircle, milli);
Maybe you can do it by keeping track of keydown and keyup event for each key and you'll know if two keys are being held at the same time.
Sample pseudo-code:
var keydown = {};
function onkeydown(event) {
keydown[event.key] = true;
}
function onkeyup(event) {
keydown[event.key] = false;
}
// in some function at some other places
if (keydown['up'] && keydown['right']) {
move_diagonal('up', 'right');
}
elseif (keydown['up'] && keydown['left']) {
move_diagonal('up', 'left');
}
elseif .. blah blah
Javascript keyboard events fire on keypress and keydown, but don't contain the additional keymask info to determine if other keys are pressed at the same time.