encompass-cs-docs/content/pong/ball/bouncing/boundaries.md

2.2 KiB

title date weight
Boundaries 2019-05-29T11:05:16-07:00 900

Now that we have bouncing capabilities, we can add them easily to other entities. Let's make boundary boxes that make the ball bounce off the sides of the game area.

PongFE/Messages/BoundarySpawnMessage.cs:

using Encompass;
using MoonTools.Structs;

namespace PongFE.Messages
{
    public struct BoundarySpawnMessage : IMessage
    {
        public Position2D Position { get; }
        public int Width { get; }
        public int Height { get; }

        public BoundarySpawnMessage(Position2D position, int width, int height)
        {
            Position = position;
            Width = width;
            Height = height;
        }
    }
}

PongFE/Engines/BoundarySpawner.cs:

using Encompass;
using PongFE.Components;
using PongFE.Messages;

namespace PongFE.Spawners
{
    public class BoundarySpawner : Spawner<BoundarySpawnMessage>
    {
        protected override void Spawn(in BoundarySpawnMessage message)
        {
            var entity = CreateEntity();

            AddComponent(entity, new PositionComponent(message.Position));
            AddComponent(entity, new CollisionComponent(new MoonTools.Bonk.Rectangle(0, 0, message.Width, message.Height)));
            AddComponent(entity, new CanCauseBounceComponent());
        }
    }
}

Now we can create the boundary entities by sending messages with WorldBuilder.

PongFEGame.cs

    ...

    WorldBuilder.AddEngine(new BoundarySpawner());

    ...

    // top boundary
    WorldBuilder.SendMessage(
        new BoundarySpawnMessage(
            new MoonTools.Structs.Position2D(0, -6),
            1280,
            6
        )
    );

    // right boundary
    WorldBuilder.SendMessage(
        new BoundarySpawnMessage(
            new MoonTools.Structs.Position2D(1280, 0),
            6,
            720
        )
    );

    // bottom boundary
    WorldBuilder.SendMessage(
        new BoundarySpawnMessage(
            new MoonTools.Structs.Position2D(0, 720),
            1280,
            6
        )
    );

Notice that we didn't have to write any new game logic to add boundaries to our game. This is the power of modular composition using ECS.