Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » Can't get the right angle...

This thread is locked; no one can reply to it. rss feed Print
Can't get the right angle...
armond
Member #8,282
January 2007

Hi guys! I thought I could get away with my hacks. But when I needed to track a certain object's angle things started to get messy.

In a certain class, I have the following code...

1 if ( s->isVisible() )
2 {
3 //wc->fireWeapon();
4
5 std::cout << "targetY: " << targetY << " sY: " << sY << std::endl;
6 std::cout << "targetX: " << targetX << " sX: " << sX << std::endl;
7 
8 int r1 = (targetY - sY);
9 int r2 = (targetX - sX);
10
11 if (r1 == 0)
12 {
13 r1 = 1;
14 }
15
16 if (r2 == 0)
17 {
18 r2 = 1;
19 }
20 
21 fixed fangle = fatan( itofix(r1 / r2) );
22 int angle = fixtoi(fangle);
23
24 std::cout << "angle: " << angle << std::endl;
25
26 wc->getCurrentWeapon()->fire(angle);
27 }

When weapon is fired and releases a projectile... The projectile moves like this...

1void Vulcan::update()
2{
3 fixed fAngle = ftofix( (angle) );
4
5 int newX = 0;
6 int newY = 0;
7
8 if (this->x < SCREEN_W)
9 {
10 newX = x + (speed * fixtoi( fcos(fAngle) ) );
11 newY = y + (speed * fixtoi( fsin(fAngle) ) );
12 move(newX, newY);
13
14 animation->animate();
15 }
16
17}

I'm aware that my code(if it ever went well) would move in only 8 directions. But I could live with that. What I don't want is that my projectile doesn't go in the right direction like when I'm on the left side, the enemy would shoot right! Thanks for the help!

Ceagon Xylas
Member #5,495
February 2005
avatar

Do you have to use fixed point? I suggest radian.

armond
Member #8,282
January 2007

Thanks for the link. BTW, it seems like functions like fatan, fcos, and fsin requires a fixed type?

Ceagon Xylas
Member #5,495
February 2005
avatar

[long time later, I realized I was mistaken. So I rewrote this to just say...]
Use cosf, sinf, and tanf for float values.

This may be the source of the problem you're having. Try something like this

if(s->isVisible()){
  float angle=atan2f(targetY-sY,targetX-sX);
  wc->getCurrentWeapon()->fire(angle);
}

void Vulcan::update() {
  if(x < SCREEN_W) {
    float newX=x+speed*cosf(angle);
    float newY=y+speed*sinf(angle);
    move(newX,newY);
  }
}

Go to: