开发者

How to move an image around with arrow keys javascript

I recently began developing a little javascript game, just for fun. 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. 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('moveIm开发者_如何学Cage()',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. 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. And make sure you have a 10x10 image called '1.png' in the same folder as the file.

<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. 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.

Within the game loop we manipulate the x and y position of the object based on its current speed. Simple: add x speed to x position, and y speed to y position. Then, we change the actual position of the element based on the current x and y coordinates.

To manipulate the x and y speeds, we take keyboard input using event handlers. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜