August 14, 2015
On Friday, 14 August 2015 at 00:06:33 UTC, Adam D. Ruppe wrote:
> On Thursday, 13 August 2015 at 23:48:08 UTC, Jack Stouffer wrote:
>> In my code, the list can have 20-30 different types of classes in it all inheriting from the same interface, and it doesn't make sense for all of those classes to implement a method that is very specific to one of the classes.
>
>
> I don't want to get too far into this since I haven't seen your code, but the function that uses this list might itself be a candidate for addition to the interface, or a second interface with that method that all the classes also inherit from (remember you can only inherit from one class in D, but you can implement as many interfaces as you want).

The code in question is a collision resolver in a 2D game that I am making. The list is a list of all of the drawable objects that the object could be colliding with. After collision is checked on each of the possible collisions, the object is placed at the last position where it was not colliding. I am using the cast in the enemy resolver where each collision is then checked to see if the collision was with the player, and if it was, the player is then given damage.

---------------------------------
class Blob : Enemy {
    ...

    final override void resolveCollisions() {
        import player : Player;

        //check for collision
        Entity[] possible_collisions = this.state_object.getPossibleCollisions(this);
        Entity[] collisions = [];

        foreach (ref entity; possible_collisions) {
            // discount any Rect that is equal to the player's, as it's probably
            // the players bounding box
            if (this.boundingBox != entity.boundingBox &&
                this.boundingBox.intersects(entity.boundingBox)) {
                collisions ~= entity;
            }
        }

        if (collisions.length > 0) {
            // If we collided with something, then put position back to its
            // original spot
            this.position = this.previous_position;

            // If we collided with the player, give the player damage
            foreach (collision; collisions) {
                // Check to see if the object collided was a player by testing the
                // result of the cast, which will return null if unsuccessful
                if (auto player = cast(Player) collision) {
                    player.damagePlayer(5, this.position, this.mass);
                }
            }
        }
    }
}
1 2
Next ›   Last »