【发布时间】:2013-12-30 02:06:18
【问题描述】:
制作一个 pong 克隆,但在运动和课程方面遇到了一些问题。所以我有一个类Game 管理类Paddle 的两个实例,并在Game 类的构造函数中启动两个不同桨类中的变量并将变量player 设置为1 或@ 987654326@ 基于类将响应运动的键。然后在Paddle 类事件函数中,我使用if(player == 1) 或if(player == 2) 来判断何时检查键以更改桨的y 速度。我遇到的问题是因为Game 类的事件函数如下所示:
void Game::events()
{
PlayerOne.events();
PlayerTwo.events();
Game_Ball.events();
}
Paddle 类的事件函数和类定义如下所示:
class Paddle
{
public:
int player;
SDL_Surface *sprite = NULL;
float x, y, w, h;
float yVel;
SDL_Rect *clip;
void events();
void logic(Uint32 deltaTicks);
void render();
Paddle();
~Paddle();
};
void Paddle::events()
{
while (SDL_PollEvent(&event))
{
Uint8 *keystates = SDL_GetKeyState(NULL);
if (player == 1)
{
if (keystates[SDLK_o] == 1)
{
yVel -= 100;
}
if (keystates[SDLK_k] == 1)
{
yVel += 100;
}
}
else
{
if (keystates[SDLK_o] == 0)
{
yVel += 100;
}
if (keystates[SDLK_k] == 0)
{
yVel -= 100;
}
}
if (player == 2)
{
if (keystates[SDLK_w] == 1)
{
yVel -= 100;
}
if (keystates[SDLK_s] == 1)
{
yVel += 100;
}
}
else
{
if (keystates[SDLK_w] == 0)
{
yVel += 100;
}
if (keystates[SDLK_s] == 0)
{
yVel -= 100;
}
}
}
}
发生了一些混淆键的事情。通常 PlayerOne 使用“O/K”移动,PlayerTwo 使用“W/S”移动,但有时我按其中一个,对面的类会移动。这似乎没有意义。这是Game类的构造函数和定义
class Game : public GameState
{
private:
int server;
TTF_Font *score = NULL;
Paddle PlayerOne;
Paddle PlayerTwo;
Ball Game_Ball;
public:
SDL_Rect clip[2];
void events();
void logic();
void render();
Game();
~Game();
};
Game::Game()
{
//RESOURSES
PlayerOne.sprite = load_image("Game_sprite.png");
PlayerTwo.sprite = load_image("Game_sprite.png");
clip[0].x = 0;
clip[0].y = 0;
clip[0].w = 20;
clip[0].h = 20;
clip[1].x = 0;
clip[1].y = 20;
clip[1].w = 20;
clip[1].h = 100;
//PLAYER ONE
PlayerOne.x = 420;
PlayerOne.y = 100;
PlayerOne.w = 60;
PlayerOne.h = 100;
PlayerOne.clip = &clip[1];
PlayerOne.yVel = 0;
PlayerOne.player = 1;
//PLAYER TWO
PlayerTwo.x = 60;
PlayerTwo.y = 100;
PlayerTwo.w = 60;
PlayerTwo.h = 100;
PlayerTwo.clip = &clip[1];
PlayerTwo.yVel = 0;
PlayerTwo.player = 2;
//BALL
Game_Ball.Ball_Bound.x = 190;
Game_Ball.Ball_Bound.y = 190;
Game_Ball.Ball_Bound.w = 60;
Game_Ball.Ball_Bound.h = 60;
Game_Ball.clip = &clip[0];
}
player 明确设置在两个对象中,Paddle 类的事件部分清楚地区分它们,那么,为什么键会混淆?我可以很容易地为第二个玩家编写另一个类,但这会效率低下,我宁愿使用同一个类的两个副本,除了键状态之外,它们的功能都相同。所以,我不确定发生了什么。
【问题讨论】:
标签: c++ class sdl game-development