finnvoor / PlaydateKit

Create games for Playdate using Swift.
https://finnvoor.github.io/PlaydateKit/documentation/playdatekit
Creative Commons Zero v1.0 Universal
198 stars 21 forks source link

Additional `userdata` on Sprite? #89

Closed paulstraw closed 3 months ago

paulstraw commented 3 months ago

Since userdata is already being used internally by the library, what are your thoughts on adding something like a userdata2 (just an example name) for end developers? My use case is an entity system where entities may have zero or more sprites. When dealing with sprite collisions later, I need some way to find the entity that a "collided with" sprite belongs to.

Thanks for your work here. I've just started messing with PlaydateKit, but it's really impressive so far!

finnvoor commented 3 months ago

The intention is that you can subclass sprite and add whatever user data you want, I.E.

class EntitySprite: Sprite.Sprite {
    let entityID: Int
}

or however else you want to do it.

Then you can get the current and collided sprite from moveWithCollisions, and compare with Equatable, conditionally cast to your sprite subclass and get custom properties, etc.

This can be seen in the Pong example, where Ball is a Sprite subclass with velocity: https://github.com/finnvoor/PlaydateKit/blob/02926e5c14b54e0b63c379879e43bcf34fc50459/Examples/Pong/Sources/Pong/Game.swift#L96-L107

and collided sprites are compared with the equatable conformance:

https://github.com/finnvoor/PlaydateKit/blob/02926e5c14b54e0b63c379879e43bcf34fc50459/Examples/Pong/Sources/Pong/Game.swift#L115-L138

I think this should cover what you want, but let me know if you run into issues or expect it to work differently.

paulstraw commented 3 months ago

Thanks for the quick response. I understand the pattern/use case you've demonstrated. I would really prefer to not subclass Sprite.Sprite though, since in my entity system not all entities have sprites.

paulstraw commented 3 months ago

Thinking about this more, I suppose what I can do is just have Sprite.Sprite subclasses that my entity classes use. Going to close, thanks again for your help.