2017-10-30 9 views
-1

私はJavascriptでサイド・スクロール・ゲームを作っていて、私のキャラクターに重力を実装する必要があります。たとえば、キャラクターは上に飛び、右にジャンプしたり、左にジャンプしたり、上矢印を押したり放したりするだけで、左または右の矢印キーで徐々に下がる必要があります。ここに私のコードは、これまでのところです:上矢印を押すと解除されたとき、私は起こるしたいのですがどのようなJavascriptゲームに重力を実装しようとしています

var gameChar_x;  //refers to the characters x position 
var gameChar_y;  //refers to the characters y position 
var floorPos_y;  //refers to the y position of the floor 
var isJumping = false; 

function draw() 

    if (isJumping == true && gameChar_y == floorPos_y) { 
    gameChar_y = gameChar_y - 9.8 //makes the character jump when on the floor 
    } 

    if (isJumping == false && gameChar_y != floorPos_y) { 
    gameChar_y = gameChar_y + 9.8 //makes the character come back down when 
    the up arrow key is released 

function keyPressed() 

    if (keyCode == UP_ARROW && gameChar_y == floorPos_y) { //jump if character is on the floor 
    isJumping = true; 
    } 

    if (keyCode == UP_ARROW && keyCode == RIGHT_ARROW) { 
    isJumping = true; 
    } 

    if (keyCode == UP_ARROW && keyCode == LEFT_ARROW) { 
    isJumping = true; 
    } 

は、文字が跳ね上がり、ゆっくりと時間に1つのピクセルずつ戻って地面に来ています。助けてくれてありがとう。

答えて

0

あなたはchar型の滴下1pxのアニメーションごとに100ミリ秒をシミュレートするために、間隔を使用して試みることができる:

// Max height a character can jump 
const MAX_JUMP_HEIGHT = 10; 
// Current position of the character 
let x_position = 0; 
let y_position = 0; 
// Timer variable 
let timer = null; 
function render() { 
    // draw the character on the screen according to the current x_position and y_position 
} 
function onJump() { 
    // If we're already jumping, we want to cancel the previous jump timeout so gravity suddenly doesn't double. 
    if (timer) clearInterval(timer); 
    // Set our current position to max jumping height. 
    y_position = MAX_JUMP_HEIGHT; 
    timer = setInterval(function() { 
     // subtract one pixel from the the current position 
     y_position--; 
     // call a render function 
     render(); 
     // Cancel the interval once we reach 0px jump height. 
     if (!y_position) clearInterval(timer); 
    }, 100); 
}; 

どこ0PXのY_POSITIONは必ずしも意志あなたは、仕事にプラットフォームのようなものを得るために数字を少し編集することができますベースラインとなり、MAX_HEIGHTをジャンプごとのオフセットとして使用したいとします。

+0

これはキャラクターのジャンプをさせていますが、降りていません。私はあまりにも理由がわからない。 – Fuzzer

関連する問題