【发布时间】:2017-08-04 21:33:55
【问题描述】:
所以我正在开发一款塔防游戏。我需要选择一个用户单击鼠标的图块(现在我只是在图块周围画一个边框)。现在我的代码有时可以工作,我不知道如何让它更好地工作。现在,当我单击一个区域时,使用我拥有的代码,该图块被选中,有时它会立即取消选择,而其他时候则不会。几乎就像我按住鼠标一样,它只是不停地“点击”鼠标。我需要的是它选择瓷砖而不取消选择它,无论按下鼠标按钮多长时间。我的鼠标输入类是这样设置的:
鼠标输入.h
#pragma once
#include <SDL.h>
class MouseInput
{
public:
MouseInput();
~MouseInput();
void Update();
bool GetMouseButton(int index);
SDL_Event GetEvent();
bool GetPressed();
bool GetReleased();
private:
void GetButtonStates();
private:
bool mouseArray[3];
int x, y;
bool justReleased;
bool justPressed;
SDL_Event e;
};
鼠标输入.cpp
#include "Input.h"
MouseInput::MouseInput()
:
x(0),
y(0),
justReleased(false),
justPressed(false)
{
SDL_PumpEvents();
for (int i = 0; i < 3; i++)
{
mouseArray[i] = false;
}
}
MouseInput::~MouseInput()
{
}
void MouseInput::Update()
{
SDL_PollEvent(&e);
justReleased = false;
justPressed = false;
if (e.type == SDL_MOUSEBUTTONDOWN && e.button.button == SDL_BUTTON_LEFT)
justPressed = true;
else if (e.type == SDL_MOUSEBUTTONUP && e.button.button == SDL_BUTTON_LEFT)
justReleased = true;
}
bool MouseInput::GetPressed()
{
return justPressed;
}
bool MouseInput::GetReleased()
{
return justReleased;
}
bool MouseInput::GetMouseButton(int index)
{
if (index <= 3 && index >= 1)
{
return mouseArray[index - 1];
}
return false;
}
SDL_Event MouseInput::GetEvent()
{
return e;
}
void MouseInput::GetButtonStates()
{
SDL_PollEvent(&e);
if (e.type == SDL_MOUSEBUTTONDOWN)
{
// 1 = Left; 2 = Center; 3 = Right
mouseArray[e.button.button - 1] = true;
}
if (e.type == SDL_MOUSEBUTTONUP)
{
mouseArray[e.button.button - 1] = false;
}
}
在我的游戏类中,我设置了鼠标输入以及一个变量来存储被点击的瓷砖的坐标。我还有一个变量pressed 来检查鼠标是否被按下。在我的更新功能中,我检查是否未按下鼠标。如果鼠标没有被按下,那么我检查鼠标是否被按下,游戏可以获得鼠标位置的坐标。我知道这听起来很疯狂,所以这是我的一些代码:
std::pair<int, int> coords; // Will store the coordinates of the tile position that the mouse rests in
bool pressed; // If the mouse was pressed (i should call it toggle because it's true if the mouse was pressed once, then false if the mouse was pressed again, then true...ect.)
更新功能
鼠标类
bool clicked; // In my custom Mouse.h file and set to false in constructor
MouseInput input; // In my custom Mouse.h file
鼠标类Update()
input.Update(); // Calls the MouseInput updating
if (input.GetPressed() && !clicked)
{
clicked = !clicked;
printf("OK");
}
//else if (clicked && input.GetReleased())
else if (clicked && input.GetPressed()) // Somewhat works. It works almost like before. If I click the mouse it shows up then sometimes when I click again it works, and other times I have to click a couple times
{
clicked = !clicked;
}
在我的游戏类中,我只是检查鼠标点击是否为真,然后画出我需要的东西
if (mouse.GetClicked())
{
// Draw what I need here.
// Currently is only drawn when I hold down the mouse
// And not drawn when I release the mouse.
}
然后当我在瓷砖周围绘制正方形时,我只在pressed = true 时绘制它。否则不绘制。此代码有时有效,有时则无效。为了得到我想要的效果,我必须真正快速地点击鼠标。如果我不这样做,有时看起来好像我正在按住鼠标按钮并且方块只是闪烁。
【问题讨论】:
-
不相关,但在
GetMouseButton我认为您的意思是index >= 1,而不是-1。 -
你说得对,哈哈。不知道为什么我有-1。这甚至没有意义哈哈。