2011-12-30 92 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