Хорошо, я искал онлайн, чтобы построить платформер, и я делаю это шаг за шагом. У меня уже есть изображения, которые мне нужны, и как их разместить на экране. Я также знаю, как делать точечную систему, но я далек от завершения. Теперь я хотел бы знать, как перемещать игрока слева направо с помощью экранных кнопок. Я ищу что-то совершенно отличное от этого кода, который я нашел здесь, поскольку он кажется слишком большим кодом, и он просто перемещает символы вправо без остановки.
Я ищу:
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>
Ну вот. Надеюсь, это не слишком много кода для вас :)
Демо JSfiddle находится здесь.
<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>
Это просто доказательство концепции.
Вы все еще далеки от выпуска Марио Бросса 25, но это шаг в правильном направлении.
Или это осталось?