2014-01-05 102 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

相关问题