[英]How can I reverse the direction of an element on a canvas?
我試圖做到這一點,以便當我的“玩家”達到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)
}
您還可以更改超時時間,以添加偽重力效果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.