NoobMe
NoobMe

Reputation: 544

Projectiles/Bullets direction Cocos2d

i am following a tutorial on a simple cocos2d game.

however on that tutorial the bullets that the user fires is only on one direction

what can i do to make it fire on all directions not just one sided?

here is the code of the direction.

int offX = location.x - projectile.position.x;
int offY = location.y - projectile.position.y;

[self addChild:projectile];

int realX = winSize.width + (projectile.contentSize.width/2);
float ratio = (float) offY / (float) offX;
int realY = (realX *ratio) + projectile.position.y;
CGPoint realDest = ccp(realX, realY);

int offRealX = realX - projectile.position.x;
int offRealY = realY - projectile.position.y;
float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
float velocity = 480/1;
float realMoveDuration = length/velocity;

[projectile runAction:[Sequence actions:[MoveTo actionWithDuration:realMoveDuration position:realDest],
                       [CallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]];

all help will be greatly appreciated. Thanks

Upvotes: 4

Views: 1048

Answers (1)

davbryn
davbryn

Reputation: 7176

Assuming you are creating the projectile at the location of your character, you just need to figure out the direction before calculating the end point.

After adding the projectile:

[self addChild:projectile];

Add a scalar float:

float scalarX = 1.0f;

And make it negative if the touch is left of the character:

if (offX < 0.0f) scalar = -1.0f;

Then just multiply the realX by this scalar to make it point the correct way

int realX = scalar * (winSize.width + (projectile.contentSize.width/2));

Upvotes: 4

Related Questions