-
Notifications
You must be signed in to change notification settings - Fork 2
ButtonExample
DrJonki edited this page Oct 3, 2014
·
7 revisions
#pragma once
#ifndef BUTTON_HPP
#define BUTTON_HPP
#include <UtH/Engine/GameObject.hpp>
#include <functional> // Needed for std::function
namespace uth
{
// RenderTarget forward declaration. If we only use pointers and/or references to a class in a header,
// we won't need the full definition (No need to include the file).
class RenderTarget;
class Texture;
}
namespace ns
{
class Button : public uth::GameObject
{
public:
// Button requires knowledge of the render target this button is used with to transform
// mouse coordinates to world coordinates.
Button(const uth::RenderTarget& target, uth::Texture* texture);
void update(float dt) override;
void setCallback(std::function<void()> callback);
private:
const uth::RenderTarget& m_target;
std::function<void()> m_callback;
};
}
#endif // BUTTON_HPP
#include <Button.hpp>
#include <UtH/Platform/Input.hpp>
#include <UtH/Renderer/RenderTarget.hpp>
#include <UtH/Engine/Sprite.hpp>
using namespace ns;
Button::Button(const uth::RenderTarget& target, uth::Texture* texture)
: GameObject(),
m_target(target)
{
// Create a new Sprite component with the loaded texture.
this->AddComponent(new uth::Sprite(texture));
}
void Button::update(float)
{
// First check if a click happened.
if (uthInput.Mouse.IsButtonPressed(uth::Mouse::LEFT))
{
// Transform the mouse position into world coordinates.
auto clickPos = m_target.PixelToCoords(uthInput.Mouse.Position());
// Check if the mouse position is inside the bounds of this object.
// Also check callback validity (has it been set?).
if (transform.GetBounds().contains(clickPos) && m_callback)
m_callback();
}
}
void Button::setCallback(std::function<void()> callback)
{
m_callback = callback;
}