Rotate object to point at mouse position

2.6k views Asked by At

I have an image of a spaceship, which I want to rotate to point at the mouse position. To calculate the angle I have to rotate I use the following code:

void CinderGaemApp::CalculateAngleBetweenMouseAndObject()
{    
  float deltaY = mouseLoc_.y - 10; //hardcoded y coordinate of the tip of the spaceship
  float deltaX = mouseLoc_.x - 0; //hardcoded x coordinate of the tip of the spaceship

  angleInDegrees_ = atan2(deltaY,deltaX) * 180 / 3.141;
}

After that I update my player object:

void Player::update(float degree)
{
  gl::pushMatrices();
    gl::translate(20,20);
    gl::rotate(degree);
    gl::translate(-20,-20);
  gl::popMatrices();
}

Then I draw it. But my problem is, when I use gl::popMatrices(), the image isnt moving at all. If I remove gl::popMatrices(), the image first spins around for 2 seconds or so and is then not pointing correct to the mouse. Is there anything wrong with my code? Please comment if you need more code, I am not really sure how much information you need.

1

There are 1 answers

1
ratchet freak On BEST ANSWER

you need to put the sequence in your render function:

void Player::render()
{
  gl::pushMatrices();
    gl::translate(position.x, position.y);
    gl::translate(20,20);
    gl::rotate(my_degree);
    gl::translate(-20,-20);
    // do other render operations
  gl::popMatrices();
}

with update simply being

void Player::update(float degree)
{
  my_degree=degree;
}

because each block between matching pushMatrix and popMatrix is independent so the code you had in your update was a noop