Aurora Engine 遊戲引擎入門 13(新增平臺的輸入)

inspironx發表於2020-12-22

#1 基本的輸入操作,滑鼠,鍵盤
#2 宣告基類,方便後續擴充和修改
#3 新增基於Window的窗體實現類


#1 基本的輸入操作,滑鼠,鍵盤


#2 宣告基類,方便後續擴充和修改

// Input.h
#pragma once

#include "Aurora/Core.h"

namespace Aurora
{
	// AURORA_API 編譯的時候會生成dll
	// 打包成庫,方便二次使用
	class AURORA_API Input
	{
	public:
		// inline 是行內函數,防止開闢過多的棧空間,進行編譯優化
		// inline 的函式一般情況下是函式體比較小,太大的函式使用inline不划算
		inline static bool IsKeyPressed(int keyCode) { return s_Instance->IsKeyPressedImpl(keyCode); }

		inline static bool IsMouseButtonPressed(int button) { return s_Instance->IsMouseButtonPressedImpl(button); }
		// pair 標準庫tuple派生的2個值的封裝,屬於攻擊模板類
		inline static std::pair<float, float> GetMousePosition() { return s_Instance->GetMousePositionImpl(); }
		inline static float GetMouseX() { return s_Instance->GetMouseXImpl(); }
		inline static float GetMouseY() { return s_Instance->GetMouseYImpl(); }
	protected:
		virtual bool IsKeyPressedImpl(int keycode) = 0;

		virtual bool IsMouseButtonPressedImpl(int button) = 0;
		virtual std::pair<float, float> GetMousePositionImpl() = 0;
		virtual float GetMouseXImpl() = 0;
		virtual float GetMouseYImpl() = 0;
	private:
		static Input* s_Instance;
	};
}

#3 新增基於Window的窗體實現類

// WindowsInput.h
#pragma once

#include "Aurora/Input.h"

namespace Aurora
{
	class WindowsInput : public Input
	{
	protected:
		virtual bool IsKeyPressedImpl(int keycode) override;

		virtual bool IsMouseButtonPressedImpl(int button) override;
		virtual std::pair<float, float> GetMousePositionImpl() override;
		virtual float GetMouseXImpl() override;
		virtual float GetMouseYImpl() override;
	};
}

// WindowsInput.cpp
#include "aopch.h"
#include "WindowsInput.h"

#include "Aurora/Application.h"
#include <GLFW/glfw3.h>

namespace Aurora {
	// 全域性定義靜態單例
	Input* Input::s_Instance = new WindowsInput();

	bool WindowsInput::IsKeyPressedImpl(int keycode)
	{
		auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
		auto state = glfwGetKey(window, keycode);
		return state == GLFW_PRESS || state == GLFW_REPEAT;
	}

	bool WindowsInput::IsMouseButtonPressedImpl(int button)
	{
		auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
		auto state = glfwGetMouseButton(window, button);
		return state == GLFW_PRESS;
	}

	std::pair<float, float> WindowsInput::GetMousePositionImpl()
	{
		auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
		double xpos, ypos;
		glfwGetCursorPos(window, &xpos, &ypos);

		return { (float)xpos, (float)ypos };
	}

	float WindowsInput::GetMouseXImpl()
	{
		auto [x, y] = GetMousePositionImpl();
		return x;
	}

	float WindowsInput::GetMouseYImpl()
	{
		auto [x, y] = GetMousePositionImpl();
		return y;
	}

}

Gitea


相關文章