I'm creating a game that needs a diagonal movement when button is pressed. Anyone, pls post a code or algo on how to implement this? I understand the the buttons only have Up,Down,Left,Right. So I want to move my object diagonal when pressed. Thanks.
How to implement Diagonal Movement?
When you detect up and left being pressed simultaneously, move your object up and left.
You normally get two events for buttons. One is when the button is pressed, and one is when the button is released. You need to maintain the state of the buttons yourself. There is no default "IsPressed(BTN_UP)" type function. So, if you get the ButtonDown() events for two directions, you'll know it's a diagonal direction.
Note I said "normally" because there actually are PDAs out there that don't send a second ButtonDown() call if a different button is already pressed. I don't think any "current" devices have that flaw.
Additionally, you could code an on-screen direction pad.
-John
Note I said "normally" because there actually are PDAs out there that don't send a second ButtonDown() call if a different button is already pressed. I don't think any "current" devices have that flaw.
Additionally, you could code an on-screen direction pad.
-John
A little bit of psuedo-code...
Obviously this is simplified as an example, but it really is that easy
- Code:
bool up = false;
bool down = false;
bool left = false;
bool right = false;
// This is the function that is called when a keyDown event occurs
void keyDown(int whatKey) {
if (whatKey == UP) {
up = true;
}
if (whatKey == DOWN) {
down = true;
}
if (whatKey == LEFT) {
left = true;
}
if (whatKey == RIGHT) {
right = true;
}
}
// This is the function that is called when keyUp events occur
void keyUp(int whatKey) {
if (whatKey == UP) {
up = false;
}
if (whatKey == DOWN) {
down = false;
}
if (whatKey == LEFT) {
left = false;
}
if (whatKey == RIGHT) {
right = false;
}
}
// This is the main loop of your application, called
// once per frame in general
void mainLoop() {
if (up) {
y = y - 1;
}
if (down) {
y = y + 1;
}
if (left) {
x = x - 1;
}
if (right) {
x = x + 1;
}
Obviously this is simplified as an example, but it really is that easy