所以我正在开发塔防游戏。我需要选择一个用户点击鼠标的图块(现在我只是在图块周围绘制边框)。现在,我有时可以使用代码,但我不确定如何让它更好地工作。现在,当我点击一个区域时,代码会被选中,有时它会立即取消选择,而其他时间则不会。几乎就像我拿着鼠标,它只是“点击”鼠标。我需要的是,无论取消选择图块,无论鼠标按钮被按下多长时间,都可以选择该图块。我的鼠标输入级的设置是这样的:SDL C++鼠标输入处理切换效果
MouseInput.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;
};
MouseInput.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;
}
}
在我的游戏类我已经安装了mouseinput以及一个变量来存储被点击的图块的坐标。我也有一个变量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
Mouse类更新()
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'。 – hnefatl
你是对的。不知道为什么我有-1。这甚至没有意义哈哈。 – Vince