It’s a bit basic question. But, I fail to understand how to solve it. I have an application which has several enteties. E.g. pike <– fish –> shark. Where fish is a base class.
I am doing some kind of lake, so all my instances of fish class can move only within some boarders. Even more, they all are randomly created on one of the edges of the lake and swim to another depending on the edge they are located at. Here is how it looks for a base class:
public class Fish extends FlxSprite
{
[Embed(source="./resources/Elipse.png")]
public var image:Class;
// Variable which stores the direction of item movement (false - Move right)
// (true - Move Left)
private var movement:Boolean;
public function Fish(x:int, y:int)
{
super(x, y, image);
// Move right
if ( x < 5 )
{
movement = false;
}
else
{
movement = true;
}
}
public override function update():void
{
if( movement )
{
this.velocity.x -= 3;
}
else
{
this.velocity.x += 3;
}
super.update();
}
Now I want to extend this model to add some extra behaviour to the fish class. E.g. I want to make a shark. To do so I need to:
1) Replace the image of abstract fish with an image of shark
2) Change the behaviour a bit (shark still needs to know about direction but maybe use another approach to velocities)
3) Define size property (e.g. based on size the shark would be stronger or weaker)
The question is:
How do I define a shark… As a subclass of Fish? Or it’s better to subclass it from Sprite?
I thought that subclassing from Fish would be more natural way, but in this case, I do not understand how to override the visual presentation of the Fish (e.g. image), as it’s impossible to override a variable.
From the other hand if I will use FlxSprite as a base class, it would be easy to redefine the presentation, but in the case I would not be able to reuse the movement code (e.g. so fish knows in which direction to swim)…
I understand that the question is a bit hard to understand. Happy to re-define it in case of any questions.
You can’t override a variable (it wouldn’t make any sense), but you can set its value in the constructor.
in
Fish:in
Shark:You could also use a getter.
In
Fish:and then in
Shark:I think overriding getters and setters is a good option for you. You could then change the behavioral velocity/size for each species.