Game Development Reference
In-Depth Information
The first thing you need to do with the file name is remove the path information from it. In order to do
that, you split up the string, using a slash (
/
) as the delimiter. You then take the final element from the
array, which should contain the full file name:
var pathSplit = imageName.split('/');
var fileName = pathSplit[pathSplit.length - 1];
The next step is removing the file extension. This means you have to call the
split
method using a
period (
.
) as the delimiter. The first element in the array will contain the file name without an extension:
var fileNameNoExt = fileName.split('.')[0];
Then you split the file name without an extension using
@
-as a delimiter, as follows:
var fileSplit = fileNameNoExt.split("@");
The
fileSplit
variable refers to an array. If
@
-doesn't appear in the string, the number of elements
in the
fileSplit
variable is 1 (the original string). If the number of elements in the array is greater
than 1, you know that the file name contains information about the dimensions of the sheet. You also
know, in that case, that the
last element
of the array contains that information. The last element is
split again using the
x
character as the delimiter. All this is expressed in the following
if
instruction:
if (fileSplit.length <= 1)
return;
var colRow = fileSplit[fileSplit.length - 1].split("x");
// deal with the sheet dimension data
Now there are two possibilities. The
colRow
array contains either one or two elements. In both cases,
you know that the first element in the array represents the number of columns in the sheet, so you
simply store it in the
_sheetColumns
variable:
this._sheetColumns = colRow[0];
If the length is two, you also need to store the second string element, in the _
sheetRows
variable:
if (colRow.length === 2)
this._sheetRows = colRow[1];
Yet another possibility is that the array contains more than two elements. You don't handle that
situation here (in that case, you only store the number of columns). In the
SpriteGameObject
class,
you assume that you store a reference to a
SpriteSheet
instead of an
Image
. The sprite sheet should
be passed as a parameter when the
SpriteGameObject
instance is created, very similar to what you
did before. You also store the current sheet index. This number indicates which element from the
sprite sheet the
SpriteGameObject
should draw. Here is the complete constructor:
function SpriteGameObject(sprite, layer, id) {
GameObject.call(this, layer, id);
this.sprite = sprite;
this.origin = Vector2.zero;
this._sheetIndex = 0;
}
Search WWH ::
Custom Search