PDA

View Full Version : How to create moving and rotating object controled from keyboard.

Xender
06-18-2013, 03:24 PM
I need to create program where i moving with WASD keys and look at mouse (this working perfectly, im using for his lookat) and i need to create Robot on scene which can be controled from keyboard, like moving forward and backward and turning right or left. I think i need glRotatef and glTranslatef to do this but i don't know how.

For now i have to global variables: robotMove, robotAngle and when i press 'i' roboteMove ++, when 'k' roboteMove --, when 'j' robotAngle++, and when 'L' robotAngle--.

Code for moving robot is:

glPushMatrix();
glRotatef(deltaKatRobot, 0, 1, 0);
glTranslatef(0, 0, deltaRuchRobot);
DrawRobot();
glPopMatrix();

This not working corectly, when my robot is in (0,0,0) point he turning corectly but when i move forward or backward he moving at circle. How to solve that?

GClements
06-18-2013, 05:41 PM
For now i have to global variables: robotMove, robotAngle and when i press 'i' roboteMove ++, when 'k' roboteMove --, when 'j' robotAngle++, and when 'L' robotAngle--
You need three parameters rather than two: an X,Y pair for the position and an angle. When the robot moves, you need to update the position according to the angle, e.g..:

void moveRobot(float distance) {
// assumes that robotAngle is in degrees clockwise from north (compass bearing)
robotX += distance * sin(robotAngle * M_PI / 180);
robotY += distance * cos(robotAngle * M_PI / 180);
}

You'd then draw the robot with:

glPushMatrix();
glTranslatef(robotX, 0, robotY);
glRotatef(robotAngle, 0, 1, 0);
DrawRobot();
glPopMatrix();

quanlong
06-24-2013, 12:22 AM
If you want the robot rotate aroud itself, firstly you must move the robot to original point, then rotate around a axis, finally move it to intial position.
For example:

glPushMatrix();
glTranslate(-originalX, -originalY, -originalZ);
glRotate(angle, 0, 1, 0);
glTranslate(originalX, originalY, originalZ);
......
glPopMatrix();