0

我正在微处理器上开发一个小游戏,我正在尝试获得一个函数,它可以根据左键按下或右键按下改变精灵向左或向右移动 90 度的方向。

目前这是我的代码。为了改变方向,不能完全执行所需的任务..

 void change_direction(Sprite * sprite) {

sprite->x += sprite->dx;//these two lines basically tell the sprite to move in whatever direction the button presses tell it to. by default it moves in a straight line in a northern direction.
sprite->y += sprite->dy;

if ( pressed( SW1 ) ) {
sprite->dx = (sprite->dy) ? -sprite->dy : 1;//this code is very broken, what it does is it moves it either diagonally upwards, or right. it should turn the sprite 90 degrees left everytime the switch is pressed.
sprite->dy = (sprite->dy) ? 0 : -sprite->dx; 
}

else if( pressed( SW0 ) ) {//this code turns the sprite right once from the default direction, but not again. what is should do is turn the sprite 90 degrees everytime.
sprite->dx = -1;
sprite->dy = 0;
}

}

我知道如何解决这个问题;按下开关不会通过在本地更改 dx dy 值来更改新方向,而是增加或减少控制方向的整数。但是,我不知道我将如何实现这样的事情。

4

2 回答 2

1

右转 90 度:

tmp = -sprite->dx;
sprite->dx = sprite->dy;
sprite->dy = tmp; 

左转90度:

tmp = sprite->dx; 
sprite->dx = -sprite->dy;
sprite->dy = tmp;

编辑:

如果您只想进行临时转换(按下按钮时),则需要在更新 x/y 时应用修饰符:

if (LEFT_BUTTON_PRESSED) {
    sprite->x -= sprite->dy;
    sprite->y += sprite->dx;
} 
else if (RIGHT_BUTTON_PRESSED) {
    sprite->x += sprite->dy;
    sprite->y -= sprite->dx;
}
else {
    sprite->x += sprite->dx;
    sprite->y += sprite->dy;
}
于 2015-05-11T12:19:12.897 回答
0

我的解决方案是这样的

typedef enum 
{
   north,
   south,
   east,
   west
}DIRECTIONS;

typedef struct
{
    uint8_t x;
    uint8_t y;
    uint8_t dx;
    uint8_t dy;
    DIRECTIONS currentDir;
}Sprite;


void change_direction (Sprite * sprite)
{
    sprite->x += sprite->dx; 
    sprite->y += sprite->dy;

    if (pressed (SW0) )
    {
       switch(sprite->currentDir)
       {
          case north:
                     sprite->dx = 1;
                     sprite->dy = 0;
                     break;
          case south:
                     sprite->dx = -1;
                     sprite->dy = 0;
                     break;
          case east:
                     sprite->dx = 0;
                     sprite->dy = 1;
                     break;
          case west:
                     sprite->dx = 0;
                     sprite->dy = -1;
                     break;
       }
   }
}
于 2015-05-11T12:51:22.857 回答