javascript 如何在javascript中用键盘移动对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23585320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to move object with keyboard in javascript
提问by Gabs
When I move the object, it's slow and doesn't move in diagonal, only up, down, right and left.
当我移动物体时,它很慢并且不会沿对角线移动,只能向上、向下、向右和向左移动。
How can I fix this, is this a good way to start or should I do it otherwise?
我该如何解决这个问题,这是一个很好的开始方式还是我应该这样做?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 600;
var object = {
height: 40,
width: 40,
x: 10,
y: 10,
color: "#FF0000"
}
document.addEventListener('keydown', function(event) {
//left
if(event.keyCode == 37) {
object.x -= 1;
}
//top
else if(event.keyCode == 38) {
object.y -= 1;
}
//right
else if(event.keyCode == 39) {
object.x += 1;
}
//bottom
else if(event.keyCode == 40) {
object.y += 1;
}
});
function renderCanvas(){
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 600, 600);
}
function renderObject(){
ctx.fillStyle = "#FF0000";
ctx.fillRect(object.x, object.y, object.width, object.height);
}
function run(){
renderCanvas();
renderObject();
}
setInterval(run, 10);
Here's a jsfiddle
这是一个jsfiddle
I'm kind of a newbie in javascript and I really need help on this ;)
我是 JavaScript 的新手,我真的需要这方面的帮助;)
回答by
Use flags or an object with flags that is updated when keys are pressed and released:
使用标志或带有标志的对象,这些标志在按下和释放键时会更新:
var Keys = {
up: false,
down: false,
left: false,
right: false
};
Then update in key events:
然后更新关键事件:
window.onkeydown = function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) Keys.left = true; // only one key per event
else if (kc === 38) Keys.up = true; // so check exclusively
else if (kc === 39) Keys.right = true;
else if (kc === 40) Keys.down = true;
};
window.onkeyup = function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) Keys.left = false;
else if (kc === 38) Keys.up = false;
else if (kc === 39) Keys.right = false;
else if (kc === 40) Keys.down = false;
};
This will now allow you to check keys that are pressed at the same time (if you want to move continuously you need to check status of the key object in a loop or else you will get a repeat delay):
这将允许您检查同时按下的键(如果您想连续移动,您需要在循环中检查键对象的状态,否则您将获得重复延迟):
if (Keys.up) {
dy+=3;
}
else if (Keys.down) { // both up and down does not work so check excl.
dy-=3;
}
if (Keys.left) {
dx+=3;
}
else if (Keys.right) {
dx-=3;
}
回答by markE
How about using the number-pad keys?
如何使用数字键盘键?
These number keys are already marked with the up/down/left/right arrowkeys so using 1,3,7,9 for diagonal moves would be understandable and convenient for the user.
这些数字键已经标有上/下/左/右箭头键,因此使用 1,3,7,9 进行对角移动对于用户来说是可以理解和方便的。
To speed up your movement, you can add more than 1 pixel with each keystroke.
为了加快移动速度,您可以在每次击键时添加 1 个以上的像素。
To move diagonally, you'll want to change both the object.x and object.y values simultaneously.
要沿对角线移动,您需要同时更改 object.x 和 object.y 值。
// move 4 pixels with each key
var distance=4;
// for example, move diagonally up & left
object.x-=distance;
object.y-=distance;
Here's example code and a Demo: http://jsfiddle.net/m1erickson/RnJLZ/
这是示例代码和演示:http: //jsfiddle.net/m1erickson/RnJLZ/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var distance=4;
var object = {
height: 40,
width: 40,
x: 10,
y: 10,
color: "#FF0000"
}
renderObject();
document.body.onkeydown=function(event){
switch(event.keyCode){
case 97: // 1
object.x-=distance;
object.y+=distance;
break;
case 98: // 2
object.x+=0;
object.y+=distance;
break;
case 99: // 3
object.x+=distance;
object.y+=distance;
break;
case 100: // 4
object.x-=distance;
object.y+=0;
break;
case 101: // 5
object.x+=0;
object.y+=0;
break;
case 102: // 6
object.x+=distance;
object.y+=0;
break;
case 103: // 7
object.x-=distance;
object.y-=distance;
break;
case 104: // 8
object.x+=0;
object.y-=distance;
break;
case 105: // 9
object.x+=distance;
object.y-=distance;
break;
}
renderObject();
}
function renderObject(){
if(ctx.fillStyle!=object.color.toLowerCase()){
console.log(ctx.fillStyle,object.color);
ctx.fillStyle=object.color;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(object.x,object.y,object.width,object.height);
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
回答by Medda86
I tried and it looks like you had to set flags. I came up with this: http://jsfiddle.net/medda86/y6WU9/
我试过了,看起来你必须设置标志。我想出了这个:http: //jsfiddle.net/medda86/y6WU9/
html
html
<div class="pic"></div>
css
css
html,body{
width:100%;
height:100%;
margin:0px;}
.pic{
position:absolute;
margin-left:100px;
margin-top:100px;
width:100px;
height:100px;
background-color:#ccc;}
jquery
查询
// MOVE OBJECT DIAGONALLY
$(document).ready(function(){
var movementSpeed = 10;
var intervalSpeed = 60;
var runAnimation = false;
var animationSpeed = 10;
var leftMarginLimit = parseInt($('.pic').parent().css('width')) - parseInt($('.pic').css('width'));
var topMarginLimit = parseInt($('.pic').parent().css('height')) - parseInt($('.pic').css('height'));
var leftMargin = parseInt($('.pic').css('margin-left'));
var topMargin = parseInt($('.pic').css('margin-top'));
var animationComplete = true;
// flags
var left = false;
var right = false;
var up = false;
var down = false;
$(document).keyup(function(key) {
if (key.which == 37){left = false;}
if (key.which == 39){right = false;}
if (key.which == 38){up = false;}
if (key.which == 40){down = false;}
});
$(document).keydown(function(key) {
if (key.which == 37){left = true;}
if (key.which == 39){right = true;}
if (key.which == 38){up = true;}
if (key.which == 40){down = true;}
});
setInterval(runMovement,intervalSpeed);
function runMovement() {
if (animationComplete){
// LEFT
if (left){
leftMargin -=movementSpeed;
if (leftMargin < 0){leftMargin = 0;}
if (leftMargin > leftMarginLimit){leftMargin = leftMarginLimit;}
}
// RIGHT
if (right){
leftMargin +=movementSpeed;
if (leftMargin < 0){leftMargin = 0;}
if (leftMargin > leftMarginLimit){leftMargin = leftMarginLimit;}
}
// UP
if (up){
topMargin -=movementSpeed;
if (topMargin < 0){topMargin = 0;}
if (topMargin > topMarginLimit){topMargin = topMarginLimit;}
}
// DOWN
if (down){
topMargin +=movementSpeed;
if (topMargin < 0){topMargin = 0;}
if (topMargin > topMarginLimit){topMargin = topMarginLimit;}
}
// ANIMATION?
if (runAnimation){
animationComplete = false;
$('.pic').animate({'margin-left': leftMargin+'px','margin-top': topMargin+'px'},animationSpeed,function(){
animationComplete = true;
});
}
else{
$('.pic').css({'margin-left': leftMargin+'px','margin-top': topMargin+'px'});
}
}
}
});
You can change theese settings, like how fast to move object and if you wanna run the animation, and set the animationspeed. Also you cna set the interval here.. game speed :P
您可以更改这些设置,例如移动对象的速度以及是否要运行动画,并设置动画速度。你也可以在这里设置间隔..游戏速度:P
var movementSpeed = 10;
var intervalSpeed = 60;
var runAnimation = false;
var animationSpeed = 10;
EDIT: I had to add the setinterval, got a bit buggy the other way with keydown and keyup. Now you can move all around more smoothly :)
编辑:我不得不添加setinterval,在keydown和keyup的另一种方式上有点问题。现在你可以更顺畅地四处走动:)
回答by Rudie
Flags, yes, but 2 is plenty: dx
and dy
:
标志,是的,但是 2 就足够了:dx
和dy
:
http://jsfiddle.net/rudiedirkx/paw4X/1/
http://jsfiddle.net/rudiedirkx/paw4X/1/
var dx = 0, dy = 0;
var speed = 100; // px per second
var activeKey = 0;
document.addEventListener('keydown', function(e) {
if (activeKey == e.keyCode) return;
activeKey = e.keyCode;
//left
if (e.keyCode == 37) {
console.log('start moving LEFT');
dx = -1;
}
//top
else if (e.keyCode == 38) {
console.log('start moving UP');
dy = -1;
}
//right
else if (e.keyCode == 39) {
console.log('start moving RIGHT');
dx = 1;
}
//bottom
else if (e.keyCode == 40) {
console.log('start moving DOWN');
dy = 1;
}
});
document.addEventListener('keyup', function(e) {
switch (e.keyCode) {
case 37: // left
case 39: // right
console.log('stop moving HOR');
dx = 0;
break;
case 38: // up
case 40: // down
console.log('stop moving VER');
dy = 0;
break;
}
activeKey = 0;
});
function fun(){
renderCanvas();
object.x += dx / 60 * speed;
object.y += dy / 60 * speed;
renderObject();
requestAnimationFrame(fun);
}
requestAnimationFrame(fun);
The ugly activeKey
part is necessary, because some keyboards repeat the keydown
event every X ms until the key is released.
丑陋的activeKey
部分是必要的,因为有些键盘keydown
每 X ms重复一次事件,直到按键被释放。
回答by Karthadon
var object = {
height: 40,
width: 40,
x: 10,
y: 10,
color: "#FF0000"
}
You seem to have forgotten a semicolon. Let me show you:
你似乎忘记了分号。我来给你展示:
var object = {
height: 40,
width: 40,
x: 10,
y: 10,
color: "#FF0000"
};