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.