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

64 lines
2.4 KiB
Markdown
Raw Normal View History

2019-05-23 19:54:38 +00:00
---
title: "Position Component"
date: 2019-05-23T11:34:58-07:00
weight: 10
---
This one is pretty simple. We can't draw something if we don't know *where* on screen to draw it.
2020-07-12 01:19:31 +00:00
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.
2019-05-23 19:54:38 +00:00
2020-07-12 01:19:31 +00:00
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.
2019-05-23 19:54:38 +00:00
2020-07-12 01:19:31 +00:00
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.
2019-05-23 19:54:38 +00:00
2020-07-12 01:19:31 +00:00
{{% 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:
2020-07-12 01:19:31 +00:00
```xml
<ItemGroup>
<PackageReference Include="MoonTools.Structs" Version="3.0.1"/>
2020-07-12 01:19:31 +00:00
</ItemGroup>
```
and PongFE.Core.csproj:
```xml
<ItemGroup>
<PackageReference Include="MoonTools.Structs" Version="3.0.1"/>
2020-07-12 01:19:31 +00:00
</ItemGroup>
```
2020-07-22 21:41:12 +00:00
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
```sh
dotnet restore
```
in the terminal.
2020-07-12 01:19:31 +00:00
Now we can define our PositionComponent. Create a file: **PongFE/Components/PositionComponent.cs**
```cs
using Encompass;
using MoonTools.Structs;
namespace PongFE.Components
{
public struct PositionComponent : IComponent
{
public Position2D Position { get; }
public PositionComponent(Position2D position)
{
Position = position;
}
}
2019-05-23 19:54:38 +00:00
}
```
2020-07-12 01:19:31 +00:00
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.