1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
#include <iostream> #include <conio.h> // For _kbhit() and _getch() // Constants for movement speed const float MOVE_SPEED = 0.5f; // Function to print the current position of the object void printPosition(float x, float y, float z) { std::cout << "Object Position - X: " << x << ", Y: " << y << ", Z: " << z << std::endl; } // Function to handle user input and move the object void handleInput(float& x, float& y, float& z) { if (_kbhit()) { char ch = _getch(); // Get the user input switch (ch) { case 'w': // Move forward z -= MOVE_SPEED; break; case 's': // Move backward z += MOVE_SPEED; break; case 'a': // Move left x -= MOVE_SPEED; break; case 'd': // Move right x += MOVE_SPEED; break; case 'q': // Move up y += MOVE_SPEED; break; case 'e': // Move down y -= MOVE_SPEED; break; case 'x': // Exit the simulation std::exit(0); break; } } } int main() { // Initial position of the virtual object float x = 0.0f; float y = 0.0f; float z = 0.0f; std::cout << "Virtual Reality Simulation\n"; std::cout << "Controls:\n"; std::cout << "W: Move Forward\n"; std::cout << "S: Move Backward\n"; std::cout << "A: Move Left\n"; std::cout << "D: Move Right\n"; std::cout << "Q: Move Up\n"; std::cout << "E: Move Down\n"; std::cout << "X: Exit Simulation\n"; while (true) { printPosition(x, y, z); handleInput(x, y, z); } return 0; } |
Explanation
- Constants:
MOVE_SPEED
: Defines how much the object moves per key press.
- printPosition Function:
- Outputs the current position of the virtual object in 3D space.
- handleInput Function:
- Handles user input to move the object.
- Uses
_kbhit()
and_getch()
from<conio.h>
to check for and get keyboard input. - Moves the object based on the pressed key:
W
moves the object forward (decreasesz
coordinate).S
moves the object backward (increasesz
coordinate).A
moves the object left (decreasesx
coordinate).D
moves the object right (increasesx
coordinate).Q
moves the object up (increasesy
coordinate).E
moves the object down (decreasesy
coordinate).X
exits the simulation.
- Main Function:
- Initializes the position of the virtual object at the origin (0,0,0).
- Displays control instructions.
- Enters an infinite loop where it continuously prints the object’s position and handles user input.
Usage
- Initial Position: The virtual object starts at the origin (0,0,0).
- Controls: Use the specified keys to move the object in 3D space. Press
X
to exit the simulation.