Game Development Reference
In-Depth Information
Drawing the sprites
Now we need to get those images onto the screen. Using DirectXTK we have access
to a class called
SpriteBatch
. If you have used XNA before, you might recognize
this class and remember that it is an excellent way to render 2D images with all of the
effort and optimization done for you.
For this we need to prepare the
SpriteBatch
inside our
Game
class so we can
render the textures we have created, and then from there add some code to the
Tex-
ture
class so that we can finally draw these images.
Let's begin by defining a shared pointer to a
SpriteBatch
object within the
Game
class. Remember that DirectXTK defines all of its classes within the DirectX
namespace, so you'll need to create something like the following:
std::shared_ptr<DirectX::SpriteBatch>
_spriteBatch;
Once you've done that, we need to create
SpriteBatch
. This requires a device con-
text so that it can create the required internal resources. Add the following line to the
start of your
LoadContent
method within the
Game
class.
Microsoft::WRL::ComPtr<ID3D11DeviceContext>
d3d11DeviceContext;
m_d3dContext.As(&d3d11DeviceContext);
_spriteBatch =
std::make_shared<DirectX::SpriteBatch>(
d3d11DeviceContext.Get()
);
Here we need to convert the device context we have from
ID3D11DeviceContext1
to
ID3D11DeviceContext
. The
ComPtr
type allows us to do this easily, and once
we have that we can create
SpriteBatch
.
Now we have a working
SpriteBatch
that can be used to render our textures. The
next step is to draw the sprites. We're using
SpriteBatch
and, as the name implies,