JS game 2d camera issue[Solved]
Posted: Fri Jun 15, 2012 2:57 pm
Hi, i've been messing around with js and canvas recently, while attempting to make an engine of some sort I've run into a problem i just can't manage to fix. I tried to make a 2d camera by positioning the player at the center and moving the enviroment but the drawing of the walls and the collision of the walls are way off! I'm using box collision and not perpixel.
her is the Rect constructor and draw functions
and here is the main loop code
map is an array of Rect objects and player is a separate object witch has a rect as a parameter.
thanks for reading.
her is the Rect constructor and draw functions
Code: Select all
function Rect(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.collidesWith = function(rect) {
if( this.y + this.h < rect.y ) return false;
if( this.y > rect.y + rect.h ) return false;
if( this.x + this.w < rect.x ) return false;
if( this.x > rect.x + rect.w ) return false;
return true;
}
}
function DrawRect(target, g){
Sstm.fillStyle="#353F3E";
Sstm.fillRect(target.x - g.rect.x,target.y - g.rect.y,target.w,target.h);
}
function DrawPlayer(target){
Sstm.fillStyle="#353F3E";
var h = target.rect.h/2;
var w = target.rect.w/2;
var y = (Scrn.height/2) - h;
var x = (Scrn.width/2) - w;
Sstm.fillRect(x,y,target.rect.w,target.rect.h);
Sstm.fillText(target.name,x,y-5);
}
Code: Select all
Sstm.clearRect(0,0,Scrn.width,Scrn.height);
switch(input){
case 115:
p.rect.y+=speed;
direction = "down";
break;
case 119:
p.rect.y-=speed;
direction = "up";
break;
case 97:
p.rect.x-=speed;
direction = "left";
break;
case 100:
p.rect.x+=speed;
direction = "right";
break;
}
for(var i=0;i<map.length;i++){
if(p.rect.collidesWith(new Rect(map[i].x - p.rect.x, map[i].y - p.rect.y, map[i].w, map[i].h))==true){
switch(direction){
case "left" : p.rect.x += speed; break;
case "right" : p.rect.x -= speed; break;
case "up" : p.rect.y += speed; break;
case "down" : p.rect.y -= speed; break;
}
}
DrawRect(map[i], p);
}
DrawPlayer(p);
input = -1;
thanks for reading.