简体   繁体   English

如何使用箭头键javascript移动图像

[英]How to move an image around with arrow keys javascript

I recently began developing a little javascript game, just for fun. 我最近开始开发一个小的JavaScript游戏,只是为了好玩。 The idea was that you controlled a little dot with the arrow keys (or awsd or i don't care what) within a box on the screen. 我的想法是你在屏幕上的一个方框内用箭头键(或者awsd或者我不关心什么)控制了一个小点。 Little rectangles would then randomly spawn on all edges of the box and progress across it. 然后,小矩形会随机产生在盒子的所有边缘上并在其上方前进。 you have to avoid contact with them. 你必须避免与他们接触。 The project turned out to be harder than I expected and I couldn't get the movement to work right. 事实证明这个项目比我预期的要困难,我无法让这项运动正常运转。 If you could help me with that that would be great. 如果你可以帮助我那将是伟大的。 also, feel free to take the concept and what little I have done so far and do whatever you want with it. 此外,随意采取这个概念,到目前为止我做了什么,并做任何你想做的事情。 I would be interested to see your results. 我很想看到你的结果。 Below is the code I used for the spawns without any of the movement scripts. 下面是我用于没有任何移动脚本的产生的代码。 I was using the basic idea of this code to do the movement: 我正在使用此代码的基本思想来进行运动:

var x = 5; //Starting Location - left
var y = 5; //Starting Location - top
var dest_x = 300;  //Ending Location - left
var dest_y = 300;  //Ending Location - top
var interval = 2; //Move 2px every initialization

function moveImage() {
    //Keep on moving the image till the target is achieved
    if(x<dest_x) x = x + interval; 
    if(y<dest_y) y = y + interval;

    //Move the image to the new location
    document.getElementById("ufo").style.top  = y+'px';
    document.getElementById("ufo").style.left = x+'px';

    if ((x+interval < dest_x) && (y+interval < dest_y)) {
        //Keep on calling this function every 100 microsecond 
        //  till the target location is reached
        window.setTimeout('moveImage()',100);
    }
}

main body: 主体:

<html>
<head>
    <style type="text/css">
        html::-moz-selection{
            background-color:Transparent;
        }

        html::selection {
            background-color:Transparent;
        }
        img.n {position:absolute; top:0px; width:5px; height:10px;}
        img.e {position:absolute; right:0px; width:10px; height:5px;}
        img.s {position:absolute; bottom:0px; width:5px; height:10px;}
        img.w {position:absolute; left:0px; width:10px; height:5px;}
        #canvas {
            width:300px;
            height:300px;
            background-color:black;
            position:relative;
        }
    </style>
    <script type="text/javascript">
    nmecount=0
        function play(){
            spawn()
            var t=setTimeout("play()",1000);
        }
        function spawn(){
            var random=Math.floor(Math.random()*290)
            var side=Math.floor(Math.random()*5)
            var name=1
            var z=10000
            if (side=1)
            {
            var nme = document.createElement('img');
            nme.setAttribute('src', '1.png');
            nme.setAttribute('class', 'n');
            nme.setAttribute('id', name);
            nme.setAttribute('style', 'left:'+random+'px;');
            nme.onload = moveS;
            document.getElementById("canvas").appendChild(nme);
            }
            if (side=2)
            {
            var nme = document.createElement('img');
            nme.setAttribute('src', '1.png');
            nme.setAttribute('class', 'e');
            nme.setAttribute('id', name);
            nme.setAttribute('style', 'top:'+random+'px;');
            nme.onload = moveW;
            document.getElementById("canvas").appendChild(nme);
            }
            if (side=3)
            {
            var nme = document.createElement('img');
            nme.setAttribute('src', '1.png');
            nme.setAttribute('class', 's');
            nme.setAttribute('id', name);
            nme.setAttribute('style', 'left:'+random+'px;');
            nme.onload = moveN;
            document.getElementById("canvas").appendChild(nme);
            }
            if (side=4)
            {
            var nme = document.createElement('img');
            nme.setAttribute('src', '1.png');
            nme.setAttribute('class', 'w');
            nme.setAttribute('id', name);
            nme.setAttribute('style', 'top:'+random+'px;');
            nme.onload = moveE;
            document.getElementById("canvas").appendChild(nme);
            }
        name=name+1
        }
    </script>
</head>
<body onLoad="play()">
<div id="canvas">
<img id="a" src="1.png" style="position:absolute; z-index:5; left:150px; top:150px; height:10px; width=10px;" />
<button onclick="moveleft()"><</button>
</body>
</html>

I can't figure out what your game is about, and so don't know what to do with that code. 我无法弄清楚你的游戏是什么,所以不知道如何处理该代码。 However, since you mentioned you were having trouble with movement, I wrote a quick JavaScript movement engine just for you, complete with acceleration and deceleration. 但是,既然你提到你在运动方面遇到了麻烦,我就为你编写了一个快速的JavaScript运动引擎,完成了加速和减速。 Use the arrow keys to move. 使用箭头键移动。 The following code represents a complete HTML document, so copy and paste it into a blank text file and save as .html. 以下代码表示完整的HTML文档,因此将其复制并粘贴到空白文本文件中并另存为.html。 And make sure you have a 10x10 image called '1.png' in the same folder as the file. 并确保在与文件相同的文件夹中有一个名为“1.png”的10x10图像。

<html>
<head>
<script type='text/javascript'>

// movement vars
var xpos = 100;
var ypos = 100;
var xspeed = 1;
var yspeed = 0;
var maxSpeed = 5;

// boundary
var minx = 0;
var miny = 0;
var maxx = 490; // 10 pixels for character's width
var maxy = 490; // 10 pixels for character's width

// controller vars
var upPressed = 0;
var downPressed = 0;
var leftPressed = 0;
var rightPressed = 0;

function slowDownX()
{
  if (xspeed > 0)
    xspeed = xspeed - 1;
  if (xspeed < 0)
    xspeed = xspeed + 1;
}

function slowDownY()
{
  if (yspeed > 0)
    yspeed = yspeed - 1;
  if (yspeed < 0)
    yspeed = yspeed + 1;
}

function gameLoop()
{
  // change position based on speed
  xpos = Math.min(Math.max(xpos + xspeed,minx),maxx);
  ypos = Math.min(Math.max(ypos + yspeed,miny),maxy);

  // or, without boundaries:
  // xpos = xpos + xspeed;
  // ypos = ypos + yspeed;

  // change actual position
  document.getElementById('character').style.left = xpos;
  document.getElementById('character').style.top = ypos;

  // change speed based on keyboard events
  if (upPressed == 1)
    yspeed = Math.max(yspeed - 1,-1*maxSpeed);
  if (downPressed == 1)
    yspeed = Math.min(yspeed + 1,1*maxSpeed)
  if (rightPressed == 1)
    xspeed = Math.min(xspeed + 1,1*maxSpeed);
  if (leftPressed == 1)
    xspeed = Math.max(xspeed - 1,-1*maxSpeed);

  // deceleration
  if (upPressed == 0 && downPressed == 0)
     slowDownY();
  if (leftPressed == 0 && rightPressed == 0)
     slowDownX();

  // loop
  setTimeout("gameLoop()",10);
}

function keyDown(e)
{
  var code = e.keyCode ? e.keyCode : e.which;
  if (code == 38)
    upPressed = 1;
  if (code == 40)
    downPressed = 1;
  if (code == 37)
    leftPressed = 1;
  if (code == 39)
    rightPressed = 1;
}

function keyUp(e)
{
  var code = e.keyCode ? e.keyCode : e.which;
  if (code == 38)
    upPressed = 0;
  if (code == 40)
    downPressed = 0;
  if (code == 37)
    leftPressed = 0;
  if (code == 39)
    rightPressed = 0;
}

</script>

</head>

<body onload="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='gray'>

   <!-- The Level -->
   <div style='width:500;height:500;position:absolute;left:0;top:0;background:black;'>
   </div>

   <!-- The Character -->
   <img id='character' src='1.png' style='position:absolute;left:100;top:100;height:10;width:10;'/>

</body>

</html>

It works as follows: There is a game loop that gets called as soon as the body loads. 它的工作原理如下:有一个游戏循环,一旦身体加载就会被调用。 This game loop calls itself every 10 millis for smooth animation. 这个游戏循环每10毫秒调用一次,以获得流畅的动画。 While it might not actually loop every 10 millis because of run-time speeds, such a low value will ensure that the frame rate is as smooth as can be for any browser. 虽然由于运行时速度,它实际上可能不会每10毫秒循环一次,但是如此低的值将确保帧速率与任何浏览器一样平滑。

Within the game loop we manipulate the x and y position of the object based on its current speed. 在游戏循环中,我们根据当前速度操纵对象的x和y位置。 Simple: add x speed to x position, and y speed to y position. 简单:将x速度添加到x位置,将y速度添加到y位置。 Then, we change the actual position of the element based on the current x and y coordinates. 然后,我们根据当前的x和y坐标更改元素的实际位置。

To manipulate the x and y speeds, we take keyboard input using event handlers. 为了操纵x和y速度,我们使用事件处理程序进行键盘输入。 Based on the key code, we set a variable which tells the game if a key is down or up. 根据密钥代码,我们设置一个变量,告诉游戏密钥是关闭还是关闭。 Based on whether the key is down or up, we accelerate or decelerate the object up to the maximum speed. 根据键是向下还是向上,我们将对象加速或减速到最大速度。 For more gradual speed-ups and slow-downs, floating point values can be used. 对于更加渐进的加速和减速,可以使用浮点值。

You should be able to get the gist of this simple engine by examining the code. 您应该能够通过检查代码来获得这个简单引擎的要点。 Hopefully this will help you in implementing your own movement engine for the game. 希望这将有助于您实现自己的游戏运动引擎。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM