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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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(45)
  8. , _theta(45)
  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. QPoint diff = (event->pos() - _lastPoint) / 2;
  17. rotate(-diff.x(), diff.y());
  18. QPoint glob = _widget->mapToGlobal(QPoint(_widget->width()/2,_widget->height()/2));
  19. QCursor::setPos(glob);
  20. _lastPoint = QPoint(_widget->width()/2,_widget->height()/2);
  21. }
  22. void FreeFlyCamera::keyPressEvent(QKeyEvent *event)
  23. {
  24. if (event->isAutoRepeat()) {
  25. return;
  26. }
  27. if (event->key() == Qt::Key_Z) {
  28. _speedVector.setX(1);
  29. }
  30. else if (event->key() == Qt::Key_S) {
  31. _speedVector.setX(-1);
  32. }
  33. else if (event->key() == Qt::Key_Q) {
  34. _speedVector.setY(1);
  35. }
  36. else if (event->key() == Qt::Key_D) {
  37. _speedVector.setY(-1);
  38. }
  39. }
  40. void FreeFlyCamera::keyReleaseEvent(QKeyEvent *event)
  41. {
  42. if (event->key() == Qt::Key_Z || event->key() == Qt::Key_S) {
  43. _speedVector.setX(0);
  44. }
  45. else if (event->key() == Qt::Key_Q || event->key() == Qt::Key_D) {
  46. _speedVector.setY(0);
  47. }
  48. }
  49. void FreeFlyCamera::updateLookAt()
  50. {
  51. Vector3D perp(_direction.getZ(), 0, -_direction.getX());
  52. perp /= perp.norm();
  53. _position += Vector3D(_direction * _speedVector.getX()).mult(_speed);
  54. _position += Vector3D(perp * _speedVector.getY()).mult(_speed);
  55. _engine->lookAt(_position, _direction + _position);
  56. }
  57. void FreeFlyCamera::rotate(float phi, float theta)
  58. {
  59. _phi = Tools::normalizeAngle(_phi + phi);
  60. if (_theta + theta >= 180.0) {
  61. theta = 179.0;
  62. }
  63. else if (_theta + theta < 1.0) {
  64. theta = 1.0;
  65. }
  66. else {
  67. _theta = Tools::normalizeAngle(_theta + theta);
  68. }
  69. float thetaRad = fabs(_theta / 180.0 * M_PI);
  70. float phiRad = _phi / 180.0 * M_PI;
  71. _direction = Vector3D(
  72. sin(thetaRad) * sin(phiRad),
  73. cos(thetaRad),
  74. sin(thetaRad) * cos(phiRad)
  75. );
  76. }