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.4KB

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(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. qDebug() << perp.getX() << perp.getY() << perp.getZ() << perp.norm() << _direction.getX() << _direction.getY() << _direction.getZ() << _direction.norm();
  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(float phi, float 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. }