【问题标题】:How to make object move in js?如何让物体在js中移动?
【发布时间】:2016-10-28 01:55:11
【问题描述】:

我正在尝试学习 javascript 中的面向对象编程,所以我尝试制作一个简单的游戏。我想做一个会动的角色。 js里面有代码:

  function move(event)
    {
var k=event.keyCode; 

var chr = {

    updown : function (){
            var y=0;
            if (k==38) 
                {--y;
            }else if (k==40)
                 {++y;}
            return y; 
        },

    leftright : function (){
        var x=0;
        if (k==37) 
            {--x;
        }else if (k==39) 
            {++x;}
        return x; 
            }


    };

    chrId.style.top = (chr.updown())+"px";
    chrId.style.left = (chr.leftright())+"px";

}

html:

    <!DOCTYPE html>
<html>
<head>

<link rel="stylesheet" type="text/css" href="jumpOPP.css">
<script src="jumpOPP.js"></script>
</head>

<body  onkeydown="move(event)">
<img id="chrId" src="TrackingDot.png" >


</body>
</html>

和 CSS:

#chrId {
    position: relative;
    top: 0px;
    left: 0px;
}

当我按住上、下、左、右时,点只会移动一个位置。如何让它一直移动 我拿着一把钥匙。我已经做到了没有 var char 移动。我使用了函数 move(event),然后使用了一个开关,案例 38、37、39 和 40,然后它改变了 style.top,但我无法在一个对象中实现。

是否可以创建一个对象 chr = {objekt motion, life, power...} 然后一个对象 ground = {some code that stops the chr} 和其他交互对象?有人可以为此推荐一个好的教程吗? :) 谢谢

【问题讨论】:

  • 函数 move() 必须通过 setTimeout 一次又一次地调用自己,因此它将以 60fps 为目标,并且在 keyUp 上,您必须通过标志变量或某些变量来终止 move() 的重复其他方式(clearTimeout)

标签: javascript 2d-games


【解决方案1】:

在这里工作 jsfiddle - http://jsfiddle.net/t5ya4j26/

在始终等于 0 的范围内定义局部变量时出错。因此,要解决此问题,您必须获取元素的当前 lefttop,而不是定义 x = 0y = 0

function move(event) {
var k = event.keyCode,
    chrId = document.getElementById('test'),
    chr = {
        updown: function () {
            var y = parseInt(getComputedStyle(chrId).top);
            if (k == 38) {
                --y;
            } else if (k == 40) {
                ++y;
            }

            return y;
        },

        leftright: function () {
            var x = parseInt(getComputedStyle(chrId).left);
            if (k == 37) {
                --x;
            } else if (k == 39) {
                ++x;
            }

            return x;
        }
    };

chrId.style.top = (chr.updown()) + "px";
chrId.style.left = (chr.leftright()) + "px";
}

document.addEventListener('keydown', move);

【讨论】:

  • 谢谢!你能给我推荐一个好的教程或一本书来学习 OOP 吗?
  • @user2980958 你刚刚开始学习 JavaScript,所以对几乎所有书籍、博客等都有帮助……只需输入搜索“JavaScript book”。您也可以在其他 SO 问题中找到答案 - stackoverflow.com/questions/11246/…
【解决方案2】:

我建议您将&lt;canvas&gt; 元素用于此类内容。但是使用window.setInterval(function, milliseconds) 让它重复运行你的“移动”功能,然后当一个键被释放时,window.onkeyup 清除那个间隔。

clearInterval(intervalName);

这需要您创建一个新的事件侦听器。不要将事件侦听器放在正文中,而是使用:

window.onkeydown = function(event) {
    var k = event.which || event.keyCode;  // This adds compatibilty across all browsers
    // Code to be run
}

【讨论】:

    【解决方案3】:

    我知道您正在寻找对象中的函数,但是使用它移动元素真的又快又容易,我今天刚为我的初学者游戏做了这个:

    var change = (parseInt(chrId.style.left.replace('%',''),10) + 3).toString() + "%"
        chrId.style.left = change
    

    如果您使用像素值移动,% 符号可以替换为“px”,而“+3”是您希望元素每次执行移动多少像素或百分比。

    通过将“左”更改为“上”也可以对上进行同样的操作。

    【讨论】:

      【解决方案4】:

      我的代码可能不符合你的喜好,但我只是想展示我如何解决这个问题,我确信有数百种更好的方法,但这个似乎为我省去了很多麻烦对于很多其他的东西。

      希望我能够理解这个问题并提供帮助,如果我不能理解,抱歉:)

      <!DOCTYPE html>
      <html>
      
      <head>
      <meta charset = "utf-8">
      <title> MOVEMENT </title>
      </head>
      
      <body>
      <script type = "text/javascript">
      //------------------------------------------------------------------------------
      // VARIABLES are set here so they're GLOBAL (everything may access them)
      //------------------------------------------------------------------------------
      
      let lock_left = true
      let lock_top = true
      let lock_right = true
      let lock_bottom = true
      
      //------------------------------------------------------------------------------
      
      let html; let htmls
      let body; let bodys
      let avatar; let avatars
      
      //------------------------------------------------------------------------------
      
      let avatar_x = 0
      let avatar_y = 0
      
      //------------------------------------------------------------------------------
      // EVERY map will be an object, and every object needs a CREATE function that
      // will happen only ONCE and an UPDATE function that will repeat itself
      //------------------------------------------------------------------------------
      
      const map_main =
      {
          create: function()
              {
                  html = document.querySelector( "html" ); htmls = html.style
                  body = document.querySelector( "body" ); bodys = body.style
              },
      
          //--------------------------------------------------------------------------
      
          update: function()
              {
                  htmls.width = "100%"
                  htmls.height = "100%"
                  htmls.margin = "0"
      
                  bodys.width = "100%"
                  bodys.height = "100%"
                  bodys.margin = "0"
      
                  bodys.backgroundColor = "rgb( 120, 200, 80 )"
              },
      }
      
      //------------------------------------------------------------------------------
      
      const map_avatar =
      {
          create: function()
              {
                  avatar = document.createElement( "div" ); avatars = avatar.style
                  body.appendChild( avatar )
              },
      
          //--------------------------------------------------------------------------
      
          update: function()
              {
                  avatars.width = "64px"
                  avatars.height = "64px"
                  avatars.backgroundColor = "rgb( 200, 80, 120 )"
      
                  avatars.position = "absolute"
                  avatars.top = avatar_y + "px"
                  avatars.left = avatar_x + "px"
              },
      }
      
      //------------------------------------------------------------------------------
      // BELOW are the 2 main gears of the engine
      //------------------------------------------------------------------------------
      
      // EVERY code that only needs to happen once is called here
      const master_create = function()
      {
          map_main.create()
          map_avatar.create()
      }
      
      //------------------------------------------------------------------------------
      
      // EVERYTHING that needs constant updates is called here
      const master_update = function()
      {
          map_main.update()
          map_avatar.update()
      
          movement()
      
          window.requestAnimationFrame( master_update )
      }
      
      //------------------------------------------------------------------------------
      // BELOW is showing how the keyboard affects the locks
      //------------------------------------------------------------------------------
      
      const press = function( pressed )
      {
          if( pressed.keyCode === 37 || pressed.keyCode === 69 ) lock_left = false
          if( pressed.keyCode === 38 || pressed.keyCode === 82 ) lock_top = false
          if( pressed.keyCode === 39 || pressed.keyCode === 70 ) lock_right = false
          if( pressed.keyCode === 40 || pressed.keyCode === 68 ) lock_bottom = false
      }
      
      //------------------------------------------------------------------------------
      
      const release = function( released )
      {
          if( released.keyCode === 37 || released.keyCode === 69 ) lock_left = true
          if( released.keyCode === 38 || released.keyCode === 82 ) lock_top = true
          if( released.keyCode === 39 || released.keyCode === 70 ) lock_right = true
          if( released.keyCode === 40 || released.keyCode === 68 ) lock_bottom = true
      }
      
      //------------------------------------------------------------------------------
      // BELOW will check the LOCKS and use them to change AVATAR_X and AVATAR_Y
      //------------------------------------------------------------------------------
      
      const movement = function()
      {
          if( lock_left === false ) avatar_x -= 10
          if( lock_top === false ) avatar_y -= 10
          if( lock_right === false ) avatar_x += 10
          if( lock_bottom === false ) avatar_y += 10
      }
      
      //------------------------------------------------------------------------------
      // BELOW we call the 2 gears and everything will work
      //------------------------------------------------------------------------------
      
      master_create() // will be called only ONCE
      master_update() // will repeat forever due to "window.requestAnimationFrame()"
      
      //------------------------------------------------------------------------------
      // LISTENERS should go after the engine starts rolling
      //------------------------------------------------------------------------------
      
      body.addEventListener( "keydown", press, false )
      body.addEventListener( "keyup", release, false )
      
      //------------------------------------------------------------------------------
      </script>
      </body>
      
      </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-02-23
        • 2017-08-04
        • 1970-01-01
        • 1970-01-01
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多