我试图做到这一点,以便当我的“玩家”达到 50 的 jumpDistance 时,它会掉下来,所以他会做一个小的“跳跃”。
此时代码可能并不完全“干净”,但我正在开始使用 Javascript。
我通过使用带有延迟的 for 循环让玩家跳跃。我试图让他以同样的方式下去,但这并没有按照我的计划进行。
** 注意:按空格键开始!
<!DOCTYPE html>
<html>
<style>
#canvas {
background-color: rgba(177, 177, 177, 1);
}
</style>
<body>
<div>
<p id="jumpDistance"></p>
<p id="jumpDirection"></p>
</div>
<canvas id="canvas" width="800" height="400"></canvas>
<script>
var canvas = document.querySelector('#canvas');
var context = canvas.getContext('2d');
var xPos = 150;
var yPos = 375;
var jumpDistance = 0;
function spelerObj() {
canvas.width=canvas.width;
context.rect(xPos, yPos, 25, 25);
context.stroke();
context.fillStyle = "#FF0000";
context.fillRect(xPos, yPos, 25, 25);
}
function jump(e) { //Here the player jumps, with a loop that calculates it's jump-distance.
//alert(e.keyCode);
if (e.keyCode == 32) {//
function upLoop() {
setTimeout(function () {
if(jumpDistance < 50) {
yPos -= 1;
jumpDistance++;
upLoop();
spelerObj();
document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
}
}, 1)
}
upLoop();
spelerObj();
}
}
document.onkeydown = jump;
</script>
</body>
</html>
最佳答案
你需要一个可以在跳转顶部切换到的下循环:
function upLoop() {
setTimeout(function() {
if (jumpDistance < 50) {
yPos -= 1;
jumpDistance++;
upLoop();
} else {
downLoop();
}
spelerObj();
document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
}, 1)
}
function downLoop() {
setTimeout(function() {
if (jumpDistance > 0) {
yPos += 1;
jumpDistance--;
downLoop();
}
spelerObj();
document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
}, 1)
}
您还可以改变超时持续时间以添加伪重力效果。
关于javascript - 如何反转 Canvas 上元素的方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42261009/