Tuesday, October 2, 2007

ShadowedObject class

Gonna talk code now. This is a new class I created. MovieClips (aka Drawable objects) are usually drawn on one side of the screen. When characters are in the same room, the objects need to be drawn on both sides. This means keeping track of two objects, and moving both of them when movement keys are pressed. It's a bit a tedious updating two objects all the time, so experimented with overriding superclass methods.

You have main one object DrawableObject (simplified) with methods relating to position:

class DrawableObject extends Object implements Drawable {

private var xx:Number;
private var yy:Number;

public function getXx():Number {
return xx;
}

public function setXx(xx:Number):Void {
this.xx = xx;
}

public function getYy():Number {
return yy;
}

public function setYy(yy:Number):Void {
this.yy = yy;
}

}


Then I created a class ShadowedObject (simplified) as follows:

class ShadowedObject extends DrawableObject {

private var shadowObj:Drawable;

public function ShadowedObject() {
super();
shadowObj = new DrawableObject();
}

function getShadowObject():Drawable {
return shadowObj;
}

// superclass override.
public function setXx(xx:Number):Void {
super.setXx(xx);
shadowObj.setXx(xx);
}

// superclass override.
public function setYy(yy:Number):Void {
super.setYy(yy);
shadowObj.setYy(yy);
}

}


so when I do this:

var someDrawableObject:Drawable = new ShadowedObject();
someDrawableObject.setXx(200);


the shadow object 'shadowObj' gets updated as well, so I don't need to duplicate calls.
It also highlights the advantages of encapsulation (i.e. using function/method calls) because I couldn't do this if I was referring to the properties directly (eg. someDrawableObject.xx, yy).

Quite surprised as it actually works!

No comments: