我正在尝试用C ++编写基本游戏代码。我有一个名为player的类,其函数名为moveLeft();它不断监视我想要在一个单独的线程中运行的“a”获取。
把它称为我认为我应该如何。我现在明白这是因为它是一个非静态函数,但我现在不确定如何做到这一点。我正在使用<thread>库。
#pragma once
class player
{
public:
player(); // Constructor
~player(); // Destructor
void moveLeft();
void moveRight();
void jump(double);
int getHealth();
double get_x_position();
double get_y_position();
double get_x_momentum();
double get_y_momentum();
bool getGrounded();
void setHealth(int);
void set_x_position(double);
void set_y_position(double);
void set_x_momentum(double);
void set_y_momentum(double);
void setGrounded(bool);
private:
int health;
bool grounded;
double x_position;
double y_position;
double x_momentum;
double y_momentum;
};
void player::moveLeft()
{
while (true)
{
while (GetKeyState(97))
{
if (grounded)
{
x_momentum -= .01;
}
else
{
x_momentum -= 0.07;
}
x_position += x_momentum;
}
}
}
我怎么想我应该设置它。
thread t1(&player::moveLeft);
t1.detach();
如果您是从类的成员函数启动线程,那么您可能正在寻找
thread t1(&player::moveLeft, this);
t1.detach();
包含this
指针的原因是每个成员函数都有一个隐藏参数,指向与之关联的对象的指针。上面代码中的this
是player*
。当然,你可以使用任何其他指向player
的指针,不一定是this
。无论你指向什么对象,成员函数都会在其体内看到它为“this object”。
如果你想这样做,你需要创建一个播放器类的实例
player *myplayer = new player(); //do this in your initializer, not for every call.
thread t1(&player::moveLeft, myplayer);
t1.detach();
如果您只想要一个播放器实例,则在另一个回复中发布的单例方法将起作用。
在适当的尊重下 - 我相信您的程序结构或一般设计是不合适的。
set_x_position()
)?但是要回答你的具体问题:
auto l = [&]() { player1.moveLeft(); }
auto t1 = std::thread{l};
t1.detach();
您可以使用std::bind
来解决此问题。
thread t1(std::bind(&player::moveLeft,this));
t1.detach();