Setting bool to false after wait time

Hey
I’m using a keypress to set a bool to true, but after a few seconds, I would like it to be set to false.

void whiteFlash::_keyPressed(int _key) {
if (_key == ‘z’) {
std::cout << “z pressed” << endl;
hit = true;
//ofSleepMillis(4000);
//hit = false;
}
}

I looked at the other questions similar to this in the forum as well as the threadExample in the openFrameWorks folder, but I can’t exactly tell how I would apply the code from these examples to what I’m using now or if they’re necessarily used for the same thing.

Here’s the header file:

#pragma once
#include “ofMain.h”

class whiteFlash {
public:

void setup();
void update();
void draw();
void _keyPressed(int _key);

whiteFlash();

ofImage phone;

bool hit = false;

};

Here’s the full cpp file:

#include “whiteFlash.h”

whiteFlash::whiteFlash() {

}

void whiteFlash::setup() {
hit = false;
phone.loadImage(“LL.jpg”);
}

void whiteFlash::update() {

}

void whiteFlash::draw() {
if (hit == true) {
phone.draw(100, 100);
}
}

void whiteFlash::_keyPressed(int _key) {
if (_key == ‘z’) {
std::cout << “z pressed” << endl;
hit = true;
//ofSleepMillis(4000);
//hit = false;
}
}

Thanks!

in h file

bool hit;
uint64_t time;

in cpp file

void ofApp::update(){
 
    if (hit == true) {
        
        if (ofGetElapsedTimeMillis() >= time + 4000) {
            
            hit = false;
            cout << "hit is set to false" << endl;
        }
    }
}

void ofApp::keyPressed(int key){
    
    if (key == 'z') {
        
        hit = true;
        time = ofGetElapsedTimeMillis();
        cout << "hit is set to true" << endl;
    }
}

This simply works although the timing may not be super accurate as it calculates the elapsedTime every frame.

This works perfectly
Thanks!