简体   繁体   中英

Using Atan2 in C++

I'm currently using atan2 to make my object (Rectangle) face the normal while moving along the curve. But for some reason the object would always face diagonally to the right even after moving beyond the middle of the curve.

This is the formula that I used:

vecdiff = Normals[counterNorm] - player.getPosition(); 
float angle = atan2(vecdiff.y, vecdiff.x)*180/PI + 90;
player.setRotation(angle);

Not really sure how to make object face the diagonally to the left after going passed the middle of the curve

Since this is two years ago, presumably you've fixed your problem, but if not, or for posterity, I think I have the/an answer. I'm working the same kind of problem (I think, @Walter is right, your question is a little sparse), but in Java, though I think that doesn't affect the issue.

Your problem is the centre of your coordinate system. The angle you are looking for is from the centre of the circle your curve is a part of, but the coordinate system that "getPosition" is working to is somewhere else. If it's like Android it's at the top left of your drawing area. I think that's probably the case since what you describe sounds like what I was getting initially.

What you have to do is find the reference point you require (the centre of that circle) and adjust the coordinates you feed to atan2 accordingly.

Since I was dealing with a circle, I sampled all the points of the circle and calculated the middle of the circle with

CentreX = minX + (maxX - minX)/2
CentreY = minY + (maxY - minY)/2

Since you say you're animating a rectangle along this path, you may still have a slight problem due to the discontinuity in atan2. I'm still working on that bit.

I hope I understood your question and the issues correctly. From what I can see you need to keep your angle between -180 and +180:

while (angle < -180){
    angle += 360;
}    
while (angle > 180){
    angle -= 360;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM