Hello I am creating a little top down 2D game and I am trying to have my player aim his gun towards my mouse position so the direction of the gun will aim towards the mouse position. I thought I had it all figured out but it just made my game screw up even more.
void Player::draw()
{
//Player
ofPushMatrix();
ofTranslate(500, 500);
ofFill();
ofSetColor(playerColor);
ofDrawCircle(x, y, r);
ofNoFill();
ofSetLineWidth(3);
ofSetColor(0, 0, 0);
ofDrawCircle(x, y, r);
ofFill();
ofSetColor(0, 0, 0);
ofDrawRectangle(x - 5, y + 25, 10, 25);
ofRotate(theta);
ofPopMatrix();
}
void Player::update()
{
xDistance = ofGetMouseX() - x;
yDistance = ofGetMouseY() - y;
theta = atan2(yDistance, xDistance) * 180 / PI;
}
Jildert
December 13, 2018, 9:38am
#2
Hi!
Here’s a working demo:
void ofApp::setup(){
x = 0; y = 0; r = 10;
}
void ofApp::draw(){
ofPushMatrix();
ofTranslate(300, 300);
ofRotateDeg(theta - 90);
ofFill();
ofSetColor(ofColor::red);
ofDrawCircle(x, y, r);
ofNoFill();
ofSetLineWidth(3);
ofSetColor(0, 0, 0);
ofDrawCircle(x, y, r);
ofFill();
ofSetColor(0, 0, 0);
ofDrawRectangle(x - 5, y + 25, 10, 25);
ofPopMatrix();
}
void ofApp::update(){
float xDistance = ofGetMouseX() - 300;
float yDistance = ofGetMouseY() - 300;
theta = atan2(yDistance, xDistance) * 180 / PI;
}
When calculating the distance you should take the absolute position of the player, so take the translation into account.
And rotate before drawing
I would save the position into a vector
ofVec2f pos;
In draw()
ofTranslate(pos.x, pos.y);
In update(){
float xDistance = ofGetMouseX() - pos.x; // Etc
edapx
December 13, 2018, 10:23am
#3
I would really discourage you to move things using ofTranslate, popMatrix and pushMatrix, it is a bad practice that can lead you to a lot of bugs. Use vectors, move things around using vectors and calculate directions using vectors. This is the best introduction you can find online about vectors https://natureofcode.com/book/chapter-1-vectors/ , @superartificial ported all the nature of code to OF a while ago https://github.com/superartificial/Nature-Of-Code-Open-Frameworks-Port/tree/master/Nature%20Of%20Code%20OF , unfortunately it is a bit outdated and it uses ofVec3f
instead glm::vec3
.
For a more concrete exampe of something moving towards the mouse position using glm::vec3
, have a look at this https://github.com/edap/udk-2019-creative-coding/tree/master/03-vectors-circle .
1 Like