【问题标题】:How to toggle click event using SDL?如何使用 SDL 切换点击事件?
【发布时间】:2018-01-22 16:05:36
【问题描述】:

我想要完成的事情:

  • 当用户在游戏中点击时,用户点击的图块会显示一个边框
  • 如果用户再次点击(任何地方)边框消失

到目前为止我所拥有的:

  • 当用户在游戏中点击时,所选图块周围会出现边框

我似乎无法弄清楚(我已经尝试了所有我能想到的)

  • 如何让边框在再次点击后消失

关于我的代码:

我有一个 MouseInput 类来检查鼠标左键是否被按下。我正在使用布尔变量来尝试切换将显示图块边框(如果单击)或不显示边框(如果再次单击)的变量。我拥有的代码将允许显示边框,但我无法让它在再次单击时消失。我无法真正展示我尝试过的所有东西(已经尝试了 2 天,但不记得我做了什么,哈哈)。这是到目前为止我的代码的摘要:

bool toggle; // Set to false in constructor
bool justPressed; // Set to false in constructor
bool justReleased; // Set to false in constructor

void Mouse::Update() // My custom mouse class Updating function (updates position, etc)
{
    input.Update(); // My MouseInput class Updating function.

    if (input.Left() && !toggle) // input.Left() checks if left mouse was pressed. True if it is pressed down, and false if it's not pressed.
    {
        // So we have pressed the mouse
        justPressed = true;
        justReleased = false;
        printf("UGH FML");
    }
    else if (!input.Left()) // So the mouse has been released (or hasn't clicked yet)
    {
        justPressed = false;
        justReleased = true;
    }

    if (justPressed)
    {
        toggle = true;
    }
}

我已经尝试了所有我能想到的将切换回 false 的方法。现在我的大脑正在受伤。可能有一个真正简单的解决方案,但我无法理解它。有什么建议吗?

【问题讨论】:

  • 类似if(event) border = !border;

标签: c++ click toggle sdl


【解决方案1】:

我认为您正在寻找的是以下代码块:

if (input.Left() && toggle) { //mouse is pressed and toggle is already true
    toggle = false;
}

您还应该删除以下代码块,因为如果您按下它,它将设置切换为真,无论切换是否已经为真:

if (justPressed) {
    toggle = true;
}

相反,您可以直接在 if 对应初始点击的内部设置切换:

if (input.Left() && !toggle) { //mouse is pressed and toggle is false
    toggle = true;
}

正如 sp2danny 所提到的,这两个块一起可以简化为:

if (input.Left()) { //mouse is pressed
    toggle = !toggle;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    相关资源
    最近更新 更多