2014-01-05 154 views
0

好的我一直在網上尋找構建平臺遊戲,我正在一步一步來。我已經有了我需要的圖像以及如何將它們放置在屏幕上。我也知道如何做點系統,但我還沒有完成。現在我想知道如何使用屏幕上的按鈕將玩家從左向右移動。我正在尋找的東西與我在此處找到的代碼完全不同,因爲它看起來像太多的代碼,它只是將字符向右移動而不停止。Javascript使用屏幕按鈕向左或向右移動圖像

我要找:

1)2個按鈕的權利和在右邊或左邊方向離開

2)按下按鈕移動播放器。

3)釋放按鈕時播放器停止移動。

// Other code 
... 
    imgObj.style.left = '0px'; 
} 
function moveRight() { 
    imgObj.style.left = parseInt(imgObj.style.left) + 1 + 'px'; 
} 
function stop() { 
    clearTimeout(animate); 
    imgObj.style.left = '0px'; 
} 
window.onload =init; 
//--> 
</script> 
</head> 
<body> 
    <form> 
     <img id="myImage" src="/images/html.gif" /> 
     <p>Click the buttons below to handle animation</p> 
     <input type="button" value="Start" onclick="moveRight();" /> 
     <input type="button" value="Stop" onclick="stop();" /> 
    </form> 
</body> 
</html> 
+0

好吧,它似乎沒有太多的代碼*我*。過去20年我見過很多:)。這種或那種方式不能在沒有定時器的JavaScript中做動畫。您可以直接使用它們,比如在您的示例中,或者通過輔助庫。 –

+0

由於某種原因,當我發佈該代碼時,大約有一半的編碼被編輯了出來。我一直在Google上搜索幾天,並找到一個可靠的例子。我只想要像馬里奧兄弟一樣向左或向右移動。如果你能指出我的一個堅實的例子,我將不勝感激。 – user3159542

回答

0

你在這裏。希望它不是太多代碼:)

JSfiddle演示是here

<head> 
<style> 
    #sprite { position:relative; } // needed for the img to be free to move around 
</style> 
<script> 
    var timer_id; // reference of the timer, needed to stop it 
    var speed = 50; // pixels/second 
    var period = 40; // milliseconds 
    var sprite; // the element that will move 
    var sprite_speed = 0; // move per period 
    var sprite_position = 100; // pixels 


    function animate() 
    { 
     sprite_position += sprite_speed; 
     if (sprite_position < 0) sprite_position = 0; 
     if (sprite_position > 200) sprite_position = 200; 
     sprite.style.left = sprite_position+'px'; 
    } 

    function move(direction) 
    { 
     if (timer_id) stop(); 
     sprite_speed = speed * period/1000 * direction; 
     timer_id = setInterval (animate, period); 
    } 

    function stop() 
    { 
     clearInterval (timer_id); 
     timer_id = null; 
    } 

    function init() 
    { 
     sprite = document.getElementById ("sprite"); // the HTML element we will move 
     animate(); // just to initialize sprite position 
    } 

    window.onload =init; // start doing things once the page has loaded 
</script> 
</head> 
<body> 
    <img id="sprite" src="http://petiteleve.free.fr/SO/yoshi.png" /> 
    <p>Click the buttons below to handle animation</p> 
    <input type="button" value="Left" onmousedown="move(-1);" onmouseup="stop();"/> 
    <input type="button" value="Right" onmousedown="move(1);" onmouseup="stop();"/> 
</body> 

這只是一個概念證明。
從發佈Mario Bross 25起,你還有很長的路要走,但這是朝正確方向邁出的一步。
還是剩下了?

+0

沒有那實際上是我正在尋找的東西,我只是通過看它才能理解它。我該如何添加你的聲望點?感謝您的簡單易讀的風格! – user3159542

+0

很高興你喜歡它。感謝提高聲譽提供,但我真的不關心那麼多。我只是在這裏幫助耀西走動;)。 –

+0

這將是一個正在進行的項目,有什麼方法我可以通過電子郵件在未來與你聯繫我承諾在我研究自己之前我不會問你任何事情。 – user3159542

相關問題