On Saturday, 23 May 2020 at 09:27:46 UTC, Tim wrote:
Hi all, I'm a little new to D and I'm wondering how I can store
a reference to the calling object. I want to create a reference
to an object's parent so that each time I go to update the
sprite, it is able to grab its position from the parent.
So if I have:
class Sprite{
/// Postional components of the sprite
int* x, y;
SDL_Surface* image_surface;
auto parent;
this(const char* path, auto parent){
writeln(*x);
this.parent = parent;
}
void update(){
// Copy loaded image to window surface
writeln("Sprites x: ", *x);
SDL_Rect dstRect;
dstRect.x = parent.x;
dstRect.y = parent.y;
SDL_BlitSurface(image_surface, null, g_surface,
&dstRect);
}
}
And call it like so:
sprite = new Sprite(path, this);
How can I make this sort of thing work? Thanks a lot in advance
for the help!
For example using a interface or a base class
```D
interface IBaseInterface
{
int x();
void x(int newX);
int y()
void y(int newY);
...
}
class Parent : IBaseInterface
{
private int x, y;
int x() { return this.x; }
void x(int newX) { this.x = newX; }
int y() { return this.y; }
void y(int newY) { this. y = newY; }
...
void f() {
auto sprite = new Sprite("foo/bar/sprite.png", this);
...
}
}
class Sprite{
IBaseInterface parent;
...
this(const char* path, IBaseInterface parent){
writeln(*x);
this.parent = parent;
}
void update(){
// Copy loaded image to window surface
writeln("Sprites x: ", *x);
SDL_Rect dstRect;
dstRect.x = parent.x;
dstRect.y = parent.y;
SDL_BlitSurface(image_surface, null, g_surface,
&dstRect);
}
}
```