Page 1 of 1

JS game 2d camera issue[Solved]

Posted: Fri Jun 15, 2012 2:57 pm
by VZdemon
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

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);
		}
and here is the main loop code

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;
map is an array of Rect objects and player is a separate object witch has a rect as a parameter.
thanks for reading.

Re: JS game 2d camera issue

Posted: Sun Jun 17, 2012 5:06 pm
by VZdemon
Is my code not understandable?

Re: JS game 2d camera issue

Posted: Sun Jun 17, 2012 7:01 pm
by Ark
on your main loop code, what is p?

Re: JS game 2d camera issue

Posted: Mon Jun 18, 2012 7:29 am
by Chris
Ark wrote:on your main loop code, what is p?
I'm guessing player.

Can we see a film or screenshot of it in action, I don't fully understand what's going wrong.

Re: JS game 2d camera issue

Posted: Wed Jun 20, 2012 9:19 pm
by VZdemon
p is the player object. here's a screen shot :

Re: JS game 2d camera issue

Posted: Thu Jun 21, 2012 6:28 pm
by VZdemon
nvm i solved it, thanks for reading though