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

96 lines
2.2 KiB
Markdown
Raw Permalink Normal View History

2020-07-15 01:50:26 +00:00
---
title: "Boundaries"
date: 2019-05-29T11:05:16-07:00
weight: 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**:
```cs
using Encompass;
using MoonTools.Structs;
namespace PongFE.Messages
{
2021-05-01 19:07:59 +00:00
public struct BoundarySpawnMessage
2020-07-15 01:50:26 +00:00
{
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**:
```cs
using Encompass;
using PongFE.Components;
using PongFE.Messages;
namespace PongFE.Spawners
{
public class BoundarySpawner : Spawner<BoundarySpawnMessage>
{
2020-07-22 01:28:40 +00:00
protected override void Spawn(in BoundarySpawnMessage message)
2020-07-15 01:50:26 +00:00
{
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**
```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.