Welcome, Guest. Please login or register.

Author Topic: C++ Trigonometry  (Read 5585 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Cymric

  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 1031
    • Show all replies
Re: C++ Trigonometry
« on: September 12, 2007, 08:29:36 AM »
I suggest you remove the '* 57.29578' bit for this part of the program. cos() and sin() require an argument in radians, not degrees. Oh, and please, do write 'double angle = ...'; angles are not integers :-). Then, to avoid those nasty type promotion rules of C++ noone---not even Karlos---can properly remember, I suggest you code as follows:

---------------------

double dx, dy, seekerspeed = SOME_DOUBLE_VAL;
double distx = playerx - x;
double disty = playery - y;
double angle = atan2(disty, distx);

dx = seekerspeed * cos(angle);
dy = seekerspeed * sin(angle);

x = x + (int)dx;
y = y + (int)dy;

----------------------

This has the advantage of keeping everything double which needs to be double right up to the point where it needs to become an integer. It's probably too C-like, but I like it this way anwyay. And I would code it in such a way that things were single rather than double, saves a lot of computational effort. Unfortunately, things are a bit iffy with the linker libraries, which sometime promote everything to double just the same.

You should also expect quite a lot of jittery behaviour when the seeker is near the target, as the number of possible directions the seeker can take is limited to a maximum of 8. A better and smoother result is obtained if you do all calculations of seeker and target movement in floating point (either free or fixed), and then translate those to screen coordinates only when you need to draw them. A little fudging is probably required to avoid exclamations of 'I WAS MILES AWAY FROM THAT BLASTED THING, ()&*)&U_&U_#Q!'
Some people say that cats are sneaky, evil and cruel. True, and they have many other fine qualities as well.