50 lines
2.5 KiB
Markdown
50 lines
2.5 KiB
Markdown
---
|
|
title: "Texture Component"
|
|
date: 2019-05-23T11:26:31-07:00
|
|
weight: 5
|
|
---
|
|
|
|
In a 2D game using FNA, the main way you will be drawing elements to the screen is via Texture2D.
|
|
|
|
Let's set up a Texture2DComponent. To create a new Component type, we define a struct that implements the IComponent interface.
|
|
|
|
Create a file: **PongFE/Components/Texture2DComponent.cs**
|
|
|
|
```cs
|
|
using Encompass;
|
|
using Microsoft.Xna.Framework.Graphics;
|
|
|
|
namespace PongFE.Components
|
|
{
|
|
public struct Texture2DComponent : IComponent, IDrawableComponent
|
|
{
|
|
public Texture2D Texture { get; }
|
|
public int Layer { get; }
|
|
|
|
public Texture2DComponent(Texture2D texture, int layer)
|
|
{
|
|
Texture = texture;
|
|
Layer = layer;
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
There's a lot of new information here, so let's break this down a bit.
|
|
|
|
*using* means that we are using functionality provided to us by another project. In this case, Encompass provides us with the IComponent and IDrawableComponent interfaces, and FNA provides us with the Texture2D class through the Microsoft.Xna.Framework.Graphics namespace.
|
|
|
|
*namespace* is used for organization and to prevent naming collisions. Let's say that we have a Texture2DComponent here, but another library that we include also defines something called Texture2DComponent. Now we have an ambiguity! Using namespaces avoids this problem.
|
|
|
|
{{% notice note %}}
|
|
Why is the namespace Microsoft.Xna.Framework instead of just FNA? Remember that FNA is a recreation of the original Microsoft XNA libary. So the namespace has to match for old code to remain compatible.
|
|
{{% /notice %}}
|
|
|
|
*public* means you would like Texture2DComponent to be accessible in other files and projects. Most of your classes and structs will be public, though there are cases where you might want them to be *private* or *internal*, for example a utility class that you don't want to expose externally.
|
|
|
|
What is IDrawableComponent? An IDrawableComponent is an interface that lets Encompass know that the Component includes a *Layer* property, which is used for rendering. Any time you want a component to be drawn in a specific order before or after other components, you will need to declare that your component implements IDrawableComponent.
|
|
|
|
Finally, that method is called a *constructor*. When we create an instance of Texture2DComponent, we will assign it a Texture2D that has stuff drawn on it and tell it which layer to use. We'll get to all that in a minute.
|
|
|
|
That's it for our component. We need one more bit of information before we can write our Renderer.
|