Hi Guys.
I know some of you will be able to help me with this, you're all geniuses.
In my game I have a static turret that can rotate easily. I cant think of the Maths to make the turret face the player at all times, so if the player moves, the turret rotates to face. The turret is static.
And on another note, if any of you guys can help me fix up the code a bit and make it better, I'd appreciate it. but if not that's cool.
if you want to download the source / game
go here
http://www.torqscrewsoftware.co.uk/Pages/Games/ComputerWorld/ComputerWorld.htm
Hope someone can help. thanks
Enemy faces player
Do you rotate the turret using an angle? If so, you can use atan2 to get the angle from the turret to the player's position.
Here's how I do it in one of my games. Realize, in this case, the enemy turns towards the player and starts moving towards him. You would use the same thing for the turret to keep pointing at the player:
For you, mpBody->p would be the position of your turret, and pPlayerBody->p would be the position of the player you want to be pointing towards. Then it's a matter of rotating your turret sprite by Angle radians (you may have to convert to degrees).
Here's the full code for my enemy update.
(This is form my old blog linked in my sig, specifically this section
cpFloat Angle = atan2(pPlayerBody->p.y - mpBody->p.y,
pPlayerBody->p.x - mpBody->p.x);
For you, mpBody->p would be the position of your turret, and pPlayerBody->p would be the position of the player you want to be pointing towards. Then it's a matter of rotating your turret sprite by Angle radians (you may have to convert to degrees).
Here's the full code for my enemy update.
/******************************************************************************
* Update() - Do enemy things
******************************************************************************/
void SmashPcEnemy::Update(cpBody *pPlayerBody)
{
U32 u32Time = timeGetTime();
// check if we need to update the movement
if (mu32LastMoveUpdate + ENEMY_UPDATE_MOVE < u32Time)
{
cpFloat Angle = atan2(pPlayerBody->p.y - mpBody->p.y,
pPlayerBody->p.x - mpBody->p.x);
// add randomization to angle
cpFloat RandomDegrees = (cpFloat)(((S32)rand() % 20) - 10);
Angle += (RandomDegrees*PI)/180.0f;
cpBodySetAngle(mpBody, Angle);
// Change force towards player
mForce = cpv(ENEMY_FORCE*cos(Angle), ENEMY_FORCE*sin(Angle));
//mpBody->f = cpv(ENEMY_FORCE*cos(Angle), ENEMY_FORCE*sin(Angle));
mu32LastMoveUpdate = u32Time;
}
mpBody->f = mForce;
if (mu32LastFire + ENEMY_REFIRE_TIME < u32Time)
{
SmashPcData::tBulletList BulletList;
mGameData.GetBulletList(BulletList);
SmashPcBullet *pBullet = new SmashPcBullet(mpApp, BulletList[0],
mpBody, mpSpace, FALSE);
mGameData.AddActiveBullet(pBullet);
mu32LastFire = u32Time;
}
}
(This is form my old blog linked in my sig, specifically this section
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement