2011-12-30 88 views
1

我在创建基于浏览器的游戏(如Travian)的地图时遇到了一些麻烦。我创建了一个将地图拖入不同方向的函数,但每次单击不同的位置时,我都会直接改变位置,然后根据需要移动它。有没有解决这个问题的方法? JQuery需要吗? (我不是在使用Javascript这么好,所以我的代码可能比周围的代码最简单的方式是什么样子有点不同)基于浏览器的游戏的地图

全文档:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Map</title> 
    <script type="text/javascript"> 

     //object of the element to be moved 
     _item = null; 

     //stores x & y co-ordinates of the mouse pointer 
     mouse_x = 0; 
     mouse_y = 0; 

     // stores top,left values (edge) of the element 
     mapdiv_x = 0; 
     mapdiv_y = 0; 

     //bind the functions 
     function move_init() 
     { 
      document.onmousemove = _move; 
      document.onmouseup = _stop; 
     } 

     //destroy the object when we are done 
      function _stop() 
     { 
      _item = null; 
     } 

     //main functions which is responsible for moving the element (div in our example) 
     function _move(e) 
     { 
      mouse_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("mapdiv").backgroundPositionX; 
      mouse_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("mapdiv").backgroundPositionY; 
      if(_item != null) 
      { 
       _item.style.backgroundPosition = "-" + (mouse_x - mapdiv_x) + "px -" + (mouse_y - mapdiv_y) + "px"; 
      } 
     } 

     //will be called when use starts dragging an element 
     function _move_item(mapdiv) 
     { 
      //store the object of the element which needs to be moved 
      _item = mapdiv; 
      mouse_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("mapdiv").backgroundPositionX; 
      mouse_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("mapdiv").backgroundPositionY; 

      oldmapdivx = _item.style.backgroundPositionX; 
      oldmapdivy = _item.style.backgroundPositionY; 

      mapdiv_x = oldmapdivx - mouse_x; 
      mapdiv_y = oldmapdivy - mouse_y; 

      mapdivx2 = mouse_x - mapdiv_x; 
      mapdivy2 = mouse_y - mapdiv_y; 
     } 
    </script> 
    <style type="text/css"> 
    #mapdiv { 
     background-image:url('images/map.png'); 
     background-repeat:no-repeat; 
     background-color:#666; 
     width:750px; 
     height:500px; 
     cursor: move; 
    } 
    </style> 
</head> 

<body onload="move_init()"> 
    <div id="mapdiv" onmousedown="_move_item(this);"></div> 
</body> 
</html> 
+1

你从来不需要JQuery,它是用JavaScript编写的,所以你总是可以重新创建它给你的东西。但是,为什么你想要,因为它使生活变得如此简单;你可能想要JQuery。这是一个很好的工具,如果你刚刚开始使用JS,它会为你节省大量的痛苦。 – acrosman 2012-01-04 19:19:13

回答

3

我看不到问题你的代码,不幸的。

如果你还没有为此编写自己的代码,但实际上有一个非常好的Jquery插件,它完全符合你的需求。它被称为Overscroll(http://www.azoffdesign.com/overscroll),为您提供这样一个系统所需的所有功能。看一看,我发现它在过去的工作中非常有用。查看代码也可以帮助您在自己的解决方案中找到问题。

+0

不错的插件:) – 2012-01-04 19:08:49