Sora
Sora

Reputation: 2551

making a gravity effect inside html5 canvas

I am trying to change the position of a circle inside a canvas using random x and y when hitting the space bar but i am stuck to figure out how I should implement a gravity effect so when the circle change it's position it come back down to the ground in a smoothy way my jsfiddle :http://jsfiddle.net/seekpunk/efcnM/5/

how can i modify my update function to succeed my gravity effect

function update() {
    $(window).keydown(function (e) {
        var spacebarHit = e.which == 32 || e.keyCode == 32 ? true : false;
        if (spacebarHit) {
             Bluecircle.y -=1;// RandomPos;
             Draw();
        }
    });
}

Upvotes: 2

Views: 635

Answers (2)

Eric
Eric

Reputation: 97571

Use Newtonian integration:

function mainLoop(dt) {
    circle.acc.x = 0
    circle.acc.y = 9.81 // positive is down

    circle.vel.x += circle.acc.x * t
    circle.vel.y += circle.acc.y * t

    circle.pos.x += circle.vel.x * t
    circle.pos.y += circle.vel.y * t

    // check if the bottom of the screen has been hit, and
    // clamp circle.poa to he within the world

    // do bounces by flipping the sign of components of circle.vel
}

function jump() {
    circle.vy = -20; // or something
}

Upvotes: 0

tewathia
tewathia

Reputation: 7298

Why not use the real-world equations of motion?

if (spacebarHit) {
             var oldPos = Bluecircle.y;
             var u = 50;
             var g = 9.81;
             var t = 0;
             var handle = setInterval(function () {
                 t++;
                 Bluecircle.y = oldPos-(((u)*t-(g/2)*t*t));
                 console.log(Bluecircle.y);
                 if (Bluecircle.y>oldPos) {
                     Bluecircle.y = oldPos;
                     clearInterval(handle);
                 }
             }, 100);

             Draw();
         }

DEMO

Upvotes: 2

Related Questions