我正在使用SDL2和C ++。
我已经上了Player
课程。它包含Input
类中的对象。
我制作了两个Player
个对象。
在Player
构造函数Player()
中,我在成员setControls()
对象Input
上调用m_Controls
。然后我在同一个对象上调用keyPressed()
。这两个函数都属于类Input
。
我的错误"在第89行,我打电话给m_Controls.keyPressed(SDL_SCANCODE_W)
。
该函数循环通过Input
成员数组m_Keys
- 玩家可以按下的键。如果它迭代的元素与传递给SDL_Scancode
的{{1}}匹配,那么它应该从keyPressed()
枚举中返回相应的值。
Controls
鉴于上面的代码,#include <SDL2/SDL.h>
#include <iostream>
enum Controls {
CONTROLS_INVALID= -1,
CONTROLS_QUIT_GAME,
CONTROLS_UP,
CONTROLS_RIGHT,
CONTROLS_DOWN,
CONTROLS_LEFT,
CONTROLS_CONFIRM
};
class Input {
private:
enum {m_NumberOfKeys= 6};
SDL_Scancode m_Keys[m_NumberOfKeys];
Controls m_PressedKey;
public:
Input(){}
~Input(){}
void setControls(SDL_Scancode up, SDL_Scancode right, SDL_Scancode down, SDL_Scancode left, SDL_Scancode confirm){
m_Keys[0]= SDL_SCANCODE_ESCAPE;
m_Keys[1]= up;
m_Keys[2]= right;
m_Keys[3]= down;
m_Keys[4]= left;
m_Keys[5]= confirm;
}
Controls keyPressed(SDL_Scancode userInput){
std::cout << "userInput: " << userInput << std::endl;
for (int i = 0; i < m_NumberOfKeys; ++i){
std::cout << i << ' ' << m_Keys[i] << std::endl;
if (m_Keys[i] == userInput){
switch (i) {
case CONTROLS_QUIT_GAME:
m_PressedKey= CONTROLS_QUIT_GAME;
break;
case CONTROLS_UP:
m_PressedKey= CONTROLS_UP;
break;
case CONTROLS_RIGHT:
m_PressedKey= CONTROLS_RIGHT;
break;
case CONTROLS_DOWN:
m_PressedKey= CONTROLS_DOWN;
break;
case CONTROLS_LEFT:
m_PressedKey= CONTROLS_LEFT;
break;
case CONTROLS_CONFIRM:
m_PressedKey= CONTROLS_CONFIRM;
break;
default:
m_PressedKey= CONTROLS_INVALID;
break;
}
}
}
std::cout << "m_PressedKey: " << m_PressedKey << std::endl;
return m_PressedKey;
}
};
class Player {
private:
static int s_IdGenerator;
int m_Id;
Input m_Controls;
public:
Player() {
m_Id= s_IdGenerator++;
std::cout << "Making player " << m_Id << std::endl;
switch (m_Id) {
case 1:
m_Controls.setControls(SDL_SCANCODE_W, SDL_SCANCODE_D, SDL_SCANCODE_S, SDL_SCANCODE_A, SDL_SCANCODE_SPACE);
break;
case 2:
m_Controls.setControls(SDL_SCANCODE_UP, SDL_SCANCODE_RIGHT, SDL_SCANCODE_DOWN, SDL_SCANCODE_LEFT, SDL_SCANCODE_SPACE);
break;
default:
break;
}
m_Controls.keyPressed(SDL_SCANCODE_W);
std::cout << "==\n";
}
~Player(){}
Input& getControls(){
return m_Controls;
}
};
int Player::s_IdGenerator= 1;
int main(int argc, char **argv) {
SDL_Init(SDL_INIT_EVERYTHING);
Player player1;
Player player2;
return 0;
}
在我制作`player``之后返回以下内容:
keyPressed()
到目前为止它还不错。 Making player 1
userInput: 26
0 41
1 26
2 7
3 22
4 4
5 44
m_PressedKey: 1
是SDL_SCANCODE_W
个控件之一,因此player1
已正确设置为m_PressedKey
。但是创建1
时的输出是
player2
由于Making player 2
userInput: 26
0 41
1 82
2 79
3 81
4 80
5 44
m_PressedKey: 0
不属于SDL_SCANCODE_W
控件,我希望将player2
设置为m_PressedKey
。它改为-1
。
当0
无效m_PressedKey
时,我必须更改以将此代码集-1
设置为keyPressed()
?
答案 0 :(得分:1)
在ctor或keyPressed方法中初始化它; m_PressedKey = CONTROLS_INVALID;默认的ctors是邪恶的:)