You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

freeflycamera.cpp 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "freeflycamera.h"
  2. #include <QCursor>
  3. #include "utils/tools.h"
  4. FreeFlyCamera::FreeFlyCamera(UGameEngine *engine, QWidget* widget)
  5. : AbstractCamera(engine, widget)
  6. , _speed(0.2)
  7. , _phi(270.0)
  8. , _theta(90.0)
  9. {
  10. _widget->setCursor(Qt::BlankCursor);
  11. _lastPoint = QPoint(_widget->width()/2,_widget->height()/2);
  12. rotate(0, 0);
  13. }
  14. void FreeFlyCamera::mouseMoveEvent(QMouseEvent *event)
  15. {
  16. double ratio = 0.5;
  17. QPoint diff = (event->pos() - _lastPoint);
  18. rotate(-diff.x() * ratio, diff.y() * ratio);
  19. QPoint glob = _widget->mapToGlobal(QPoint(_widget->width()/2,_widget->height()/2));
  20. QCursor::setPos(glob);
  21. _lastPoint = QPoint(_widget->width()/2,_widget->height()/2);
  22. }
  23. void FreeFlyCamera::keyPressEvent(QKeyEvent *event)
  24. {
  25. if (event->isAutoRepeat()) {
  26. return;
  27. }
  28. if (event->key() == Qt::Key_Z) {
  29. _speedVector.setX(1);
  30. }
  31. else if (event->key() == Qt::Key_S) {
  32. _speedVector.setX(-1);
  33. }
  34. else if (event->key() == Qt::Key_Q) {
  35. _speedVector.setY(1);
  36. }
  37. else if (event->key() == Qt::Key_D) {
  38. _speedVector.setY(-1);
  39. }
  40. }
  41. void FreeFlyCamera::keyReleaseEvent(QKeyEvent *event)
  42. {
  43. if (event->key() == Qt::Key_Z || event->key() == Qt::Key_S) {
  44. _speedVector.setX(0);
  45. }
  46. else if (event->key() == Qt::Key_Q || event->key() == Qt::Key_D) {
  47. _speedVector.setY(0);
  48. }
  49. }
  50. void FreeFlyCamera::updateLookAt()
  51. {
  52. Vector3D perp(_direction.getZ(), 0, -_direction.getX());
  53. perp /= perp.norm();
  54. _position += Vector3D(_direction * _speedVector.getX()).mult(_speed);
  55. _position += Vector3D(perp * _speedVector.getY()).mult(_speed);
  56. _engine->lookAt(_position, _direction + _position);
  57. }
  58. void FreeFlyCamera::rotate(double phi, double theta)
  59. {
  60. _phi = Tools::normalizeAngle(_phi + phi);
  61. if (_theta + theta >= 180.0) {
  62. theta = 179.0;
  63. }
  64. else if (_theta + theta < 1.0) {
  65. theta = 1.0;
  66. }
  67. else {
  68. _theta = Tools::normalizeAngle(_theta + theta);
  69. }
  70. float thetaRad = fabs(_theta / 180.0 * M_PI);
  71. float phiRad = _phi / 180.0 * M_PI;
  72. _direction = Vector3D(
  73. sin(thetaRad) * sin(phiRad),
  74. cos(thetaRad),
  75. sin(thetaRad) * cos(phiRad)
  76. );
  77. }