2007년 12월 21일
자바스크립트로 만드는 객체지향 게임 - 스프라이트 관리
우선 구글과 같은 형태로 스프라이트 이미지들을 한 이미지로 놓고 잘라쓰는 클래스를 만들었습니다.
/* 스트라이트통합이미지를관리하는클래스*/
$class({
CSpriteBase : {
SINGLETON : true,
imgURL : '/bomblink/img/sprite.gif',
spriteSize:[
[29,29], // bomb
[32,32] // fire
],
spritePos : [
[[0,0],[29,0],[58,0],[87,0],[0,29],[29,29]], // bomb + explosion
[[0,58],[32,58]] // fire
],
/* create sprite */
get : function(index,parent) {
var ret=new CSprite(this.spriteSize[index][0],this.spriteSize[index][1],this.imgURL,this.spritePos[index],parent);
return ret;
}
}
});
/* 분할된스프라이트이미지를표시하는div 래핑클래스*/ $class({ CSprite : { element : null, arrPos : null, curShape : null, parentPos:null, /* 통합이미지에서잘라내어div로표시하는element를생성한다*/ init : function(width,height,url,arrPos,parent) { this.element=document.createElement('div'); $style(this.element,'background','transparent url(/bomblink/img/sprite.gif) no-repeat 0px 0px'); $style(this.element,'backgroundPosition','0px 0px'); $style(this.element,'styleFloat','left'); $style(this.element,'position','absolute'); $style(this.element,'zIndex','1'); $dom.hide(this.element); if(parent) this.parentPos=$dom.getPos(parent); parent = parent || document.body; parent.appendChild(this.element); $dom.setSize(this.element,width,height); this.arrPos=arrPos; this.shape(0); }, /* 스프라이트의모양을바꾼다*/ shape : function(index) { this.curShape=index; $style(this.element,'backgroundPositionX',-this.arrPos[index][0]+'px'); $style(this.element,'backgroundPositionY',-this.arrPos[index][1]+'px'); }, /* 스프라이트를보인다*/ show : function() { $dom.show(this.element); }, /* 스프라이트를숨긴다*/ hide : function() { $dom.hide(this.element); }, /* 스프라이트위치를지정한다. parentElement를지정하면, 이에대한상대좌표로지정할수있다. */ setPos : function(x,y,parentElement) { $dom.setPos(this.element,x,y,parentElement); }, /* 스프라이트위치를얻는다. parentElement를지정하면, 이에대한상대좌표를반환한다. */ getPos : function(parentElement) { return$dom.getPos(this.element,parentElement); }, /* 스프라이트를표시하는div를반환*/ getElement : function() { returnthis.element; }, /* 스프라이트의현재모양을반환*/ getShape : function() { returnthis.curShape; } } });
이 클래스는 싱글턴 인스턴스로 생성되어 get호출시 해당 번호에 맞는 스프라이트를 잘라낸 클래스를 생성하여 반환합니다.
실제 분할된 이미지를 관리하는 클래스는 아래와 같습니다.
사용법은 $factory.get(CSpriteBase).get(0) 과 같이 합니다. 이 경우 0번 스프라이트를 반환하며, 화면에 이 스프라이트를 표시하는 div를 보여줍니다.
이 클래스는 좀 더 다듬으면 범용으로 사용할 수 있을것 같습니다.
# by | 2007/12/21 16:33 | SWAF - 응용 | 트랙백 | 덧글(0)




☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]