Consider the following simple structs:
struct Monster {
// ...
}
struct Player {
// ...
}
struct Missile {
// ...
//target: ???,
}
When writing game logic, it is very common to have objects refer to each other. In the example above, we have the structs Monster
, Player
and Missile
to illustrate the kinds of interactions needed.
Imagine we have the following traits: Position
and Think
. All the above structs implements Position
, and all except Missile
implements Think
.
The first thing to note is that Missile
is a homing missile: It stores a target and whenever the game updates Missile
objects, it will move it toward it's target.
As far as I can tell, it is impossible to sensibly store the target of this Missile
in Rust.
Obviously, the missile doesn't own its target. It just wants to access its Position
trait. The game objects must be shared, through Rc
or Gc
. But it's not like the Missile
can just store a Weak<???>
reference to something with a Position
trait. A Box<Position>
means consuming whatever object had that trait. A Box<Any>
does not allow downcasting to traits.
Making Missile<T>
and storing the target as Weak<T>
doesn't help. How would those Missile<T>
be stored? In one Collection<T>
for each kind of object the missile targets? Game objects will need to be more generic, and the dreadful Box<Any>
seems inevitable.
I'm rather new to Rust. It baffles my mind that this is straight out impossible. Surely, I must be missing something?
GameObject
and embrace theEntity
(component system) ;-) - user395760