Game Development Reference
In-Depth Information
Implementing the Sprite class
In the
Sprite
class, we initialize our
SquareGeometry
and
SpriteTexture
classes.
Open the
Sprite.js
file from
client/primitive/game
in your editor.
The
Sprite
class is a general class and inherits the
StageObject
class:
Sprite= inherit(StageObject, function (){
superc(this);
this.geometry=new SquareGeometry();
It uses the date function to create the unique
textureIndex
and
canvasId
variables:
var currentDate=new Date();
this.textureIndex=currentDate.getMilliseconds();
this.materialFile=this.textureIndex;
this.canvasId="c_"+this.textureIndex;
For each sprite object, we create a new
canvas
element and add it to our HTML
body. Then, we initialize our
SpriteTexture
class by passing the ID for our
newly created
canvas
element. Also, note that we have set the
style
attribute of
the
canvas
element to
display:none
so that it is not visible to the user, using the
following code:
jQuery("body").append("<canvas id='"+this.canvasId+"'
style='display:none'></canvas>");
this.spriteTexture=new SpriteTexture(this.canvasId);
this.backgroundColor="#ffffff";
this.color="#333333";
Also, as the default scale is (1, 1, 1), we increased the size for our sprite by scaling it
using the following line of code:
this.scale=vec3.fromValues(10,10,10);
});
The following function,
drawText
, in turn invokes the
createTexture
function of
the
SpriteTexture
class:
Sprite.prototype.drawText=function(text){
this.spriteTexture.backgroundColor=this.backgroundColor;
this.spriteTexture.color=this.color;
this.spriteTexture.createTexture(text);
}