Firing projectiles + rotation and angle with cocos2d

Official forum for the Chipmunk2D Physics Library.
Post Reply
imrank1
Posts: 1
Joined: Thu Jun 11, 2009 12:52 am
Contact:

Firing projectiles + rotation and angle with cocos2d

Post by imrank1 »

Hi :

I am trying to make a game where I have a character positioned at the bottom of the screen ( in portrait mode ). However the character does not move ( This is by design, as I want him to stay in one position ) . Whenever the user touches the screen. I want to the sprite to rotate to that position and fire off a bullet in that direction. My sprite rotates correctly so that character looks like he rotates to the correct position however my code to apply a velocity vector to the bullets is not working. Can someone point me in the right direction?

The code is modeled off of the example posted on : http://morethanmachine.com/macdev

Here is my touchesBegan method :

- (BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{


UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView: [touch view]];

point = [[Director sharedDirector] convertCoordinate: point];
NSLog(@"Clicked x=%f y=%f", point.x, point.y);
//x1 and y1 represent the place where the soldier is on the screen
double x1 = 150 ;
double y1 = 50;
double y2 = point.y;
double x2 = point.x;


double soldierAngle ;
if ( y2 < 50 && x2 <150)
{
//prevent from rotating past -90 degrees
soldierAngle = -90;


}
else if ( y2 < 50 && x2 >150)
{
// prevent from rotating past 90 degrees
soldierAngle = 90;

}
else if ( x2 < 150 )
{
//if user touched greater than 150
soldierAngle=atan ( (x1 - x2)/(y1-y2) ) * 180/PI ;
}
else if ( x2 > 150 )
{
//if user touched less than 180
soldierAngle = atan ( (x2-x1)/(y2-y1)) * 180/PI;

}



NSLog ( @"Soldier Angle is %f", soldierAngle ) ;


[soldier runAction:[RotateTo actionWithDuration:0.0
angle:soldierAngle]];

for(Bullet *b in bullets)
{
if()
{

[b fireFromTo:soldier.position.x y:soldier.position.y a:(-CC_DEGREES_TO_RADIANS(soldierAngle))];
[b setReady: NO];
break;
}
}


return kEventHandled;
}


And here is my fireBullets Method :

-(void)fireFromTo: (float)x y:(float)y a:(float)a
{
bulletBody->p = cpv(x,y);
bulletBody->v = cpv(cos(a)*320,sin(a)*480);

}


The bullets are initialized like so :

-(cpBody *) makeBulletX: (float) x y:(float) y
{
Sprite *laser = [[Sprite spriteWithFile:@"redBullet.png"] retain];
[self addChild: laser];

cpVect verts[] = {
cpv(-7,-10),
cpv(-7, 10),
cpv(7, 10),
cpv(7,-10),
};

cpBody *laserBod = cpBodyNew(100.0f, INFINITY);
laserBod->p = cpv(x, y);
laserBod->v = cpv(0, 0);

cpSpaceAddBody(space, laserBod);

cpShape * laserShape = cpPolyShapeNew(laserBod, 4, verts, cpvzero);
laserShape->e = 0.9f; laserShape->u = 0.9f;
laserShape->data = laser;
laserShape->collision_type = 1; //this is new!
cpSpaceAddShape(space, laserShape);

return laserBod;

}


Thanks for the help.
Post Reply

Who is online

Users browsing this forum: No registered users and 13 guests