2D画像の描画座標
2D画像を描画するときは、Drawメソッドで描画座標を指定しています。
m_sprites->Draw(m_texture1.Get(), XMFLOAT2(10, 75), nullptr, Colors::White);
この場合、左上からx軸が10px、y軸が75pxずれた位置に描画されます。
2Dアニメーションとは
2Dで描画している画像がスラスラと移動するアニメーション、これは画像の「移動」と「描画」を高速に繰り返し行うことで実現できます。
市販の2Dゲームが動いて見えるのも、同じ仕組で実現されています。
ゲームを実行するマシンのスペックが高ければ、フレームレート(1秒間に描画する回数)を上げることができ、より動きが滑らかになります。
レンダラーをアニメーションさせてみる
DirectXでは描画する物体をレンダラーとして扱います。
レンダラーではUpdateメソッドでレンダラーの状態の更新、Renderメソッドでレンダラーの描画を行います。
なのでUpdateメソッドで描画座標の移動、Renderメソッドで描画を連続的に行うことでレンダラーでのアニメーションを実現することができます。
では前回作成したTestRenderer.hのprotectedメソッドにXMFLOAT2型のメンバーを追加しましょう。
//画像の描画座標 XMFLOAT2 position;
コンストラクタではpositionメンバを初期化しましょう
//コンストラクタ TestRenderer::TestRenderer(const shared_ptr<DeviceResources>& deviceResources) :m_deviceResources(deviceResources){ position.x = 0; position.y = 0; }
Updateメソッドで座標を更新します。
Updateメソッドは1秒間に60回呼び出されるので
x座標を0.5ずつプラス、y座標を0.2ずつプラスしています。
//更新 void TestRenderer::Update(StepTimer const&timer){ position.x += 0.5; position.y += 0.2; }
最後にRenderメソッドでDrawメソッドを呼び、第二引数にXMFLOT2型の座標を入れます。
//描画 void TestRenderer::Render(){ m_sprites->Begin(); m_sprites->Draw(m_texture1.Get(),position, nullptr, Colors::White); m_sprites->End(); }
全体的なコードとしてはこんな感じ
TestRenderer.h
#pragma once #include "Common/DeviceResources.h" #include "Common/StepTimer.h" #include "SpriteBatch.h" #include "WICTextureLoader.h" using namespace DX; using namespace std; using namespace DirectX; using namespace Microsoft::WRL; class TestRenderer { public: TestRenderer(const shared_ptr<DeviceResources>& deviceResources); void CreateResources(); void ReleaseResources(); void Update(StepTimer const& timer); void Render(); protected: // デバイス リソース shared_ptr<DeviceResources> m_deviceResources; //2Dスプライト shared_ptr<SpriteBatch> m_sprites; //2Dテクスチャ ComPtr<ID3D11ShaderResourceView> m_texture1; //画像の描画座標 XMFLOAT2 position; };
TestRenderer.cpp
#include "pch.h" #include "TestRenderer.h" using namespace std; using namespace DX; //コンストラクタ TestRenderer::TestRenderer(const shared_ptr<DeviceResources>& deviceResources) :m_deviceResources(deviceResources){ position.x = 0; position.y = 0; } //リソース確保 void TestRenderer::CreateResources(){ auto device = m_deviceResources->GetD3DDevice(); auto context = m_deviceResources->GetD3DDeviceContext(); m_sprites=shared_ptr<SpriteBatch>(new SpriteBatch(context)); CreateWICTextureFromFile(device, L"assets/icon.png", nullptr, m_texture1.ReleaseAndGetAddressOf()); } //リソース解放 void TestRenderer::ReleaseResources(){ m_sprites.reset(); m_texture1.Reset(); } //更新 void TestRenderer::Update(StepTimer const&timer){ position.x += 0.5; position.y += 0.2; } //描画 void TestRenderer::Render(){ m_sprites->Begin(); m_sprites->Draw(m_texture1.Get(),position, nullptr, Colors::White); m_sprites->End(); }
SmapleGameDX_3_2DAnimation.zip