Ship movement + Guiding projectiles toward ship

Started by
5 comments, last by GearWorld 9 years, 8 months ago

Hi guys,

I have the following code where Projectiles are guided toward the ship.


DeltaX = (_ShipPosX + _Ship.Width / 2) - Projectile.PositionX;
DeltaY = (_ShipPosY + _Ship.Height / 2) - Projectile.PositionY;
Angle = Math.Atan2(DeltaY, DeltaX) * 180 / Math.PI;

Projectile.SetPosition(Projectile.PositionX += Math.Cos(Angle) * General.MonsterProjectileSpeed, Projectile.PositionY += Math.Sin(Angle) * General.MonsterProjectileSpeed);

It is fine when the ship doesn't move but when the ship starts to move, the projectile is rotating around itself. I'm wondering what I'm missing to make the projectile continue its course. I tried to figure this out since a week or two now without success. I was hoping someone could shed some light on it.

You can see the effect here : https://skydrive.live.com/redir?resid=7056CFFE05236B7D!919&authkey=!AF1Ef24BdnDgYT4&ithint=video%2c.mp4

Thank you for any help.

Advertisement

If Math.Atan2 returns an angle in radians, then it's entirely probable that Math.Cos and Math.Sin expect the angles passed in to be in radians as well.

That's why there's * 180 / Math.PI and this is put in a variable in Radian and passed to COS and SIN.

This formula works ok and it follows the ship all right but when the ship moves it's not suppose to rotate around itself during the ship moving but just continue its path to follow the ship since both moves !

I think what jHaskell is saying is that you SHOULDN'T use the 180/Pi. What all the math functions return is in radians and they are expecting any angles as parameters be radians.

You are converting the result of atan2() to degree !

"Angle = Math.Atan2(DeltaY, DeltaX) * 180 / Math.PI;"

So, you need to change it to

"Angle = Math.Atan2(DeltaY, DeltaX);"

Angle would be needed only to orient a sprite (e.g. an oblong rocket) or to simulate rotational dynamics. The code example can be simplified to use vectors and normalize the length of (DeltaX,DeltaY) without trigonometric functions:


DeltaX = (_ShipPosX + _Ship.Width / 2) - Projectile.PositionX;
DeltaY = (_ShipPosY + _Ship.Height / 2) - Projectile.PositionY;

Scale=General.MonsterProjectileSpeed / Math.Sqrt(DeltaX*DeltaX+DeltaY*DeltaY);

Projectile.PositionX += DeltaX*Scale; 
Projectile.PositionY += DeltaY*Scale; 

Omae Wa Mou Shindeiru

You are converting the result of atan2() to degree !

"Angle = Math.Atan2(DeltaY, DeltaX) * 180 / Math.PI;"

So, you need to change it to

"Angle = Math.Atan2(DeltaY, DeltaX);"

This works fine. Thank you very much !

This topic is closed to new replies.

Advertisement