
|
| Sprite Object TemplateIn order to use the sprite object, all you need to include is the following JS -
var i,si,co,sh,sw; si=new Array(360); co=new Array(360); for(i=0;i<360;i++){ si[i]=Math.sin(i*Math.PI/180); co[i]=Math.cos(i*Math.PI/180); } function sprite(w,h,dv,con){ sw=document.body.clientWidth; sh=document.body.clientHeight; this.frict=0.98; this.width=w; this.height=h; this.dv=document.getElementById(dv); this.boundry=con; this.bearing=0; this.power=0; this.visible=1; this.xPos=0; this.yPos=0; this.xSpd=0; this.ySpd=0; this.vector=vect; this.collide=coll; this.getBearing=gbr; this.hide=hid; } function vect(){ var chr,i,xp,yp,twd,thi; twd=this.width*.5; thi=this.height*.5; this.xSpd=this.xSpd*this.frict+si[this.bearing]*this.power; this.ySpd=this.ySpd*this.frict+co[this.bearing]*this.power; this.xPos+=this.xSpd; this.yPos-=this.ySpd; chr=this.boundry.charAt(0); if(chr=="l"){ xp=Math.max(this.xPos,twd); xp=Math.min(xp,sw-twd); if(xp==twd || xp==sw-twd){this.xSpd=0;} this.xPos=xp; }else{ if(this.xPos<twd){this.xPos+=sw;} if(this.xPos>sw-twd){this.xPos-=sw;} } chr=this.boundry.charAt(1); if(chr=="l"){ yp=Math.max(this.yPos,thi); yp=Math.min(yp,sh-thi); if(yp==thi || yp==sh-thi){this.ySpd=0;} this.yPos=yp; }else{ if(this.yPos<thi){this.yPos+=sh;} if(this.yPos>sh-thi){this.yPos-=sh;} } this.dv.style.top=this.yPos-thi+"px"; this.dv.style.left=this.xPos-twd+"px"; } function coll(spr){ var hit,xLap,yLap,xRan,yRan; xLap=Math.abs(this.xPos-spr.xPos); yLap=Math.abs(this.yPos-spr.yPos); xRan=(this.width+spr.width)*0.5; yRan=(this.height+spr.height)*0.5; if(xLap<xRan && yLap<yRan){hit=1;}else{hit=0;} return(hit); } function gbr(spr){ var bear,xLap,yLap; xLap=this.xPos-spr.xPos; yLap=spr.yPos-this.yPos; bear=Math.atan(xLap/yLap)*180/3.141; if(yLap>0){bear+=180;} if(xLap>0 && yLap<0){bear+=360;} bear=Math.round(bear); return(bear); } function hid(){ this.visible=1-this.visible; switch(this.visible){ case 0: this.dv.style.visibility="hidden"; break; case 1: this.dv.style.visibility="visible"; break; } } In order to use this object properly, there are some things you should know about the properties and methods involved -
There are also two arrays, "si" and "co", which are needed by the vector() method to operate correctly. Please regard these arrays as read-only. Also, due to the nature of the document.body object, please only create new sprite objects in function calls. The sprite object may be applied to a global variable, eg -
var mySprite;
function setup(){ mySprite=new sprite(width,height,div,"ww"); } | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||