encompass-cs-docs/content/pong/draw_paddle/position_component.md

2.4 KiB

title date weight
Position Component 2019-05-23T11:34:58-07:00 10

This one is pretty simple. We can't draw something if we don't know where on screen to draw it.

Well, why didn't we put that in the Texture2DComponent? The reason is that position is a concept that is relevant in more situations than just drawing. For example: collision, yeah? So it really should be its own component.

As with most concepts in game programming, we find that something as simple as position is a little more nuanced than appears at first glance. Think about your computer monitor. How is it drawing things? Your screen is divided into millions of little points, and each point lights up a certain color. These are pixels. So... what is a fraction of a pixel? Doesn't really make sense right? It would be much easier for us to think of position as being based on integers rather than decimals.

However, if you treat positions as simple integer pixels, you will run into problems if you ever have movement speeds based on fractions (which are very useful). Fortunately, I have created a system for handling this! It's called MoonTools.Structs. Let's add it as a dependency.

{{% notice info %}} There are actually techniques for subpixel rendering. But let's ignore that for now. {{% /notice %}}

Let's add the MoonTools.Structs package as a PackageReference in PongFE.Framework.csproj:

  <ItemGroup>
    <PackageReference Include="MoonTools.Structs" Version="3.0.1"/>
  </ItemGroup>

and PongFE.Core.csproj:

  <ItemGroup>
    <PackageReference Include="MoonTools.Structs" Version="3.0.1"/>
  </ItemGroup>

Once you have added the package reference, the project must be "restored" to bring the types in. This is done automatically during the build process, but you can trigger it manually by doing Ctrl-Shift-P -> .NET: Restore Project in VSCode, or by doing

dotnet restore

in the terminal.

Now we can define our PositionComponent. Create a file: PongFE/Components/PositionComponent.cs

using Encompass;
using MoonTools.Structs;

namespace PongFE.Components
{
    public struct PositionComponent : IComponent
    {
        public Position2D Position { get; }

        public PositionComponent(Position2D position)
        {
            Position = position;
        }
    }
}

That's it! Notice how short and readable these definitions are so far? I hope you're starting to notice the power of modularity here.