I actually managed to do it!
With some help from codinowl of course...
Because my js file is 147 lines (until now at least) i'll try to explain it as good as i can...
(by the way it's a top down game, moving in the y axis)
1st i made two global vars:
Code: Select all
var pos = new Array();//array used in moveCamera
var p = new b2Vec2();//vector is defined which will store the current y-coordinate
then in the page loader event:
Code: Select all
pos[0] = (car.GetWorldCenter().y);//initial position of object is stored
then the actual function:
Code: Select all
function moveCamera(){
//stuff needed for moveCamera
var eye = ($("#container").height())/20;//Veiwport height
var can_height = ($("#game").height())/20;//canvas height
var car_pos = (car.GetWorldCenter().y);//Initial pos. of car.
var half_eye = (eye/2);
//move the camera
var length = pos.length;
var s = ((pos[length-1]-pos[length-2]))*20;//in pixels. finds out the distance moved in one timestep
if ((half_eye < (can_height - p)) && (p > half_eye)){//checks if object is not in eye/2. Thus can be translated
cxt.translate(0, -s);//canvas is translated
}
//end move camera
}
and lastly it's needed to put this function into the gameloop function. Beware though, there should be a specific order that all the different function should be placed. Meaning, some should be before others, and some after other.
If the order is not correct you'll have to deal with weird bugs.
Code: Select all
window.setInterval(update, 1000/60);
function update(){
world.Step(1/60, 10, 10);
world.DrawDebugData();
world.ClearForces();
Rendering();
moveCar();
//getting new position in each step
p = (car.GetWorldCenter().y);
pos.push(p);
///////////////////////////////////
moveCamera();
};
I really hope this post will help someone and save a looooot of frustration.