Vishnu
Vishnu

Reputation: 2452

Game using html5 - Character jump with time limit

My explanation may be unclear and if so, please leave a comment for further clarification.

I am trying to make the character to jump to the height of the screen.
So far, this is my code:

 var limit = 0;
    function jump()
    {

    ball.posy -=10;
    limit++;


    if(limit>screenheight) 
    {
    //if character reached top of screen stop this jump() function
    isjump = false;
    limit = 0;
    }


    }

Above code will enable the character to jump up to the screen height. But if the screen height is smaller (for example, in some mobile device), character jump will be faster.
If there are any game developers who have idea, would you be able to guide me? :) Thank you.

Upvotes: 0

Views: 241

Answers (1)

bto.rdz
bto.rdz

Reputation: 6720

ok the problem is that you need to know the speed of your jump first. now its is doing it depending of your screen for example:

function jump()
   myjump += 10 // this is what you are doing now
{

so lets fix that function, how? lets make that 10 variable depending on the screen height

lets say your screen now is 800px heigh so for a 800px height screen you will add 10px, but for a 400 heigth screen you only need to add 5px!!.

so how we do it?

with this simple formula

var scaleJump = 10 * (screenHeigth/800)

function jump()
   myjump += scaleJump
{

so now if your screen heigth is 800 your var scaleJump will be = 10 * ( 800 / 800 ) = 10

and if your screen heigth is 400 scaleJump will be = 10 * ( 400 / 800 ) = 5

so problem solved!! it will increase 5 if screen is 400 and 10 if screen is 800, and scale as needed if anyonther heigth

to fix time

ok how do we know the time it takes to draw a frame?

since: fps = frames / second

so:   1/fps = seconds / frame

this is a differential equation where you have a deltaTime and a deltaDistance

DeltaTime is equals to:

1/fps

and DeltaDistance would be this, if fps were always the same, but like they are not I explain below:

10 * (screenHeigth/800)

now lets set a base speed wich you can change acording to your needs as I dont have your code I am not sure if this will move fast or slow, but you can test it and change it as you need it.

lets set speed to 1 (I dont know if it is fast or slow, just change it latter)

 since speed = DeltaDistance / DeltaTime

so lets get the distance you have to add so the speed is the same:

DeltaDistance = Speed * DeltaTime

now your code will look like this

var DeltaDistance;
var DeltaTime = (1 / fps)
var mySpeed = 1

function jump()
   DeltaDistance = mySpeed * DeltaTime
   myJump += DeltaDistance
{

I miss college :(

Upvotes: 2

Related Questions