如何在javascript中使用键盘移动对象

时间:2014-05-10 19:24:22

标签: javascript html canvas keylistener frame-rate

当我移动物体时,它很慢并且不会在对角线上移动,只能向上,向下,向右和向左移动。

我该如何解决这个问题,这是一个好的开始方式,还是我应该这样做?

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

这里是jsfiddle

我是javascript的新手,我真的需要帮助;)

5 个答案:

答案 0 :(得分:6)

使用带有标志的标志或对象,按下并释放按键时更新标志:

var Keys = {
        up: false,
        down: false,
        left: false,
        right: false
    };

然后更新关键事件:

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

这将允许您检查同时按下的按键(如果您想连续移动,您需要在循环中检查密钥对象的状态,否则您将得到重复延迟):

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

<强> FIDDLE

答案 1 :(得分:0)

如何使用数字键盘?

这些数字键已经标有向上/向下/向左/向右箭头键,因此使用1,3,7,9进行对角移动对于用户来说是可以理解和方便的。

为了加快移动速度,每次按键都可以添加超过1个像素。

要对角移动,您需要同时更改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;

以下是示例代码和演示: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>

答案 2 :(得分:0)

我试过,看起来你必须设置标志。我想出了这个:http://jsfiddle.net/medda86/y6WU9/

HTML

<div class="pic"></div>

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

        }
    }
});

您可以更改设置,例如移动对象的速度以及是否要运行动画,以及设置动画速度。你也可以在这里设置间隔..游戏速度:P

var movementSpeed = 10;
var intervalSpeed = 60;
var runAnimation = false;
var animationSpeed = 10;
编辑:我必须添加setinterval,使用keydown和keyup以另一种方式获得一些bug。现在你可以更顺利地四处移动:)

答案 3 :(得分:0)

标志,是的,但是2很多:dxdy

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

丑陋的activeKey部分是必要的,因为有些键盘每隔X ms重复一次keydown事件,直到密钥被释放。

答案 4 :(得分:0)

    var object = {
height: 40,
width: 40,
x: 10,
y: 10, 
color: "#FF0000"        
    }
你似乎忘记了分号。让我告诉你:

    var object = {
height: 40,
width: 40,
x: 10,
y: 10, 
color: "#FF0000"        
};