box2d impulse on release - iphone

i wanted to apply impulse when i release my finger but however i couldn't get it to work. the object body will not re-act to my input. so here's my code for release.
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (mouseJoint != nil) return;
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
float distanceX = location.x-170;
float distanceY =location.y-270;
float distance = sqrtf(distanceX*distanceX+distanceY*distanceY);
CGFloat angle = atan2f(distanceY,distanceX);
// Apply an impulse to the body, using the angle
tailBody->ApplyLinearImpulse(b2Vec2(-distance*cosf(angle)/4+100,-distance*sinf(angle)/4+100), tailBody->GetPosition());
if (mouseJoint) {
world->DestroyJoint(mouseJoint);
mouseJoint = NULL;
}
}
is there something missing from the code?

Related

Throw an object in swipe direction with angle and force in BOX2d

I want to throw an object on touches ended method with force and left to right direction.I created world and body object and calculated swipe distance, angle and force but it is not working properly. Here is my code- --
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"tocuehs began");
UITouch *touch=[touches anyObject];
point1 = [touch locationInView:[touch view]];
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch=[touches anyObject];
point2 = [touch locationInView:[touch view]];
float distance = ccpDistance(point1, point2);
int maxDistance = 50;
CGFloat strength = distance / maxDistance;
CGFloat angle = atan2f(point2.y - point1.y, point2.x - point1.x);
angle = - 1 * CC_DEGREES_TO_RADIANS(angle);
// int force = strength * maxForce;
_body->ApplyLinearImpulse(b2Vec2(10.0f+cos(angle)*25.0f,10.0f+sin(angle)*25.0f), _body->GetPosition());
}
Please help!

Image rotation is slow on touches moved

I have written a program that will rotate my imageView as i want (CW or ~CW).
And it is working fine.
but it is responding very slowly, I want it to respond quickly...
can you please help me out of it?
Thanks in advance...!
Following is my code------------------------
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [[event allTouches]anyObject];
CGPoint prevLoc = [touch previousLocationInView:self];
CGPoint loc = [touch locationInView:self];
if (isRotating) {
float prevAngle = atan2(prevLoc.y-self.center.y,
prevLoc.x-self.center.x);
float newAngle = atan2( loc.y-self.center.y,
loc.x-self.center.x);
float finalAngle =angle+(newAngle-prevAngle);
//Apply new transform
CGAffineTransform rotateTransform = CGAffineTransformMakeRotation(Angle);
self.transform=rotateTransform;
angle = finalAngle;
}
}

Content updating slow on screen though FPS is 60

I am loading a menu in which i have 7 layers through which i swipe. On first load the swiping is smooth at 60fps, but i then pop the scene and push it again, the swiping is very slow, though the app displays 60fps, and the ccTouchesMoved is called roughly at the same interval as on the first load.
On each layer, i add some statical CCSprites and a CCMenu.
All items are deallocated, and i am testing the app on ipad 3 (so speed isn't quite an issue).
I presume that the cause is more on the settings part and would like to find a solution for it. Here are my touch methods, if it helps:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
//Swipe Detection Part 1
firstTouch = location;
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouches = [event allTouches];
UITouch * touch = [[allTouches allObjects] objectAtIndex:0];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CGSize winSize = [[CCDirector sharedDirector] winSize];
for(int i=0;i<[layerList count];i++)
{
[[layerList objectAtIndex:i] setPosition:CGPointMake((i-currentLayer)*winSize.width + (location.x - firstTouch.x),0) ];
}
}
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouches = [event allTouches];
UITouch * touch = [[allTouches allObjects] objectAtIndex:0];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
//Swipe Detection Part 2
lastTouch = location;
//Swipe Detection Part 2
lastTouch = location;
//Minimum length of the swipe
float swipeLength = ccpDistance(firstTouch, lastTouch);
//Check if the swipe is a left swipe and long enough
if (firstTouch.x > lastTouch.x && swipeLength > 60) {
[self doStuffLeft];
}
else if (firstTouch.x < lastTouch.x && abs(swipeLength) > 60) {
[self doStuffRight];
}
}
Figured it out, [CCDirector sharedInstance] was paused.

Rotating Sprite with Touch - Cocos2d

Does anyone have a better way to rotate a sprite with one finger? My problem is that I can not get the sprite to stop rotating after it has been fully rotated twice and I flip my screen 180 degree periodcally (self.rotation = 180;) then flip it back (self.rotation = 0). But, when I flip it to 180 degrees the sprite will not rotate properly.
Any one have any better ideas than this?
CGFloat gRotation;
- (void)update:(ccTime)delta
{
g.rotation = gRotation;
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
if (CGRectContainsPoint(g.boundingBox, location))
{
CGPoint firstLocation = [touch previousLocationInView:[touch view]];
CGPoint location = [touch locationInView:[touch view]];
CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
CGPoint firstTouchingPoint = [[CCDirector sharedDirector] convertToGL:firstLocation];
CGPoint firstVector = ccpSub(firstTouchingPoint, g.position);
CGFloat firstRotateAngle = -ccpToAngle(firstVector);
CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);
CGPoint vector = ccpSub(touchingPoint, g.position);
CGFloat rotateAngle = -ccpToAngle(vector);
CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);
gRotation += currentTouch - previousTouch;
}
}
Thanks
EDIT:
I went in to GameConfig.h and changed #define GAME_AUTOROTATION kGameAutorotationUIViewController to #define GAME_AUTOROTATION kGameAutorotationNone
Then, went in to AppDelegate.m and changed #if GAME_AUTOROTATION == kGameAutorotationUIViewController to #if GAME_AUTOROTATION == kGameAutorotationNone
That fixed the sprite's rotation when I flipped the screen, but I am still having problems stopping the sprite's rotation after two full rotations.
add a new line at the end:
gRotation += currentTouch - previousTouch;
gRotation = fmod(gRotation,360.0); // <<< fix the angle
this maybe fix your problem, because the angle will stay in the 360 range
Other way to rotate with one finger is the UIPanGestureRecognizer (but you still need to keep the angle in the 360 range):
UIPanGestureRecognizer *gestureRecognizer = [[[UIPanGestureRecognizer alloc] initWithTarget:layer action:#selector(handlePanFrom:)] autorelease];
[[[CCDirector sharedDirector] openGLView] addGestureRecognizer:gestureRecognizer];
...
- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer
{
CGPoint translation = [recognizer translationInView:recognizer.view];
...
}
Take a look at this tutorial for more details (its on drag, but show how to do the pan gesture):
http://www.raywenderlich.com/2343/how-to-drag-and-drop-sprites-with-cocos2d

Implementing touch-based rotation in cocoa touch

I am wondering what is the best way to implement rotation-based dragging movements in my iPhone application.
I have a UIView that I wish to rotate around its centre, when the users finger is touch the view and they move it. Think of it like a dial that needs to be adjusted with the finger.
The basic question comes down to:
1) Should I remember the initial angle and transform when touchesBegan is called, and then every time touchesMoved is called apply a new transform to the view based on the current position of the finger, e.g., something like:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self]; //current position of touch
if (([touch view] == self)
&& [Utility getDistance:currentPoint toPoint:self.middle] <= ROTATE_RADIUS //middle is centre of view
&& [Utility getDistance:currentPoint toPoint:self.middle] >= MOVE_RADIUS) { //will be rotation gesture
//remember state of view at beginning of touch
CGPoint top = CGPointMake(self.middle.x, 0);
self.initialTouch = currentPoint;
self.initialAngle = angleBetweenLines(self.middle, top, self.middle, currentPoint);
self.initialTransform = self.transform;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self]; //current position of touch
if (([touch view] == self)
&& [Utility getDistance:currentPoint toPoint:self.middle] <= ROTATE_RADIUS
&& [Utility getDistance:currentPoint toPoint:self.middle] >= MOVE_RADIUS) { //a rotation gesture
//rotate tile
float newAngle = angleBetweenLines(self.middle, CGPointMake(self.middle.x, 0), self.middle, currentPoint); //touch angle
float angleDif = newAngle - self.initialAngle; //work out dif between angle at beginning of touch and now.
CGAffineTransform newTransform = CGAffineTransformRotate(self.initialTransform, angleDif); //create new transform
self.transform = newTransform; //apply transform.
}
OR
2) Should I simply remember the last known position/angle, and rotate the view based on the difference in angle between that and now, e.g.,:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self]; //current position of touch
if (([touch view] == self)
&& [Utility getDistance:currentPoint toPoint:self.middle] <= ROTATE_RADIUS
&& [Utility getDistance:currentPoint toPoint:self.middle] >= MOVE_RADIUS) { //will be rotation gesture
//remember state of view at beginning of touch
CGPoint top = CGPointMake(self.middle.x, 0);
self.lastTouch = currentPoint;
self.lastAngle = angleBetweenLines(self.middle, top, self.middle, currentPoint);
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self]; //current position of touch
if (([touch view] == self)
&& [Utility getDistance:currentPoint toPoint:middle] <= ROTATE_RADIUS
&& [Utility getDistance:currentPoint toPoint:middle] >= MOVE_RADIUS) { //a rotation gesture
//rotate tile
float newAngle = angleBetweenLines(self.middle, CGPointMake(self.middle.x, 0), self.middle, currentPoint); //touch angle
float angleDif = newAngle - self.lastAngle; //work out dif between angle at beginning of touch and now.
CGAffineTransform newTransform = CGAffineTransformRotate(self.transform, angleDif); //create new transform
self.transform = newTransform; //apply transform.
self.lastTouch = currentPoint;
self.lastAngle = newAngle;
}
The second option makes more sense to me, but it is not giving very pleasing results (jaggy updates and non-smooth rotations). Which way is best (if any), in terms of performance?
Cheers!
It is actually much simpler than what you have tried.
You need three data points:
The origin of your view.
The location of the current touch
The location of the previous touch
The Touch object passed to you actually contains the last touch location. So you don't need to keep track of it.
All you have to do is calculate the angle between two lines:
Origin to Current Touch
Origin to Previous Touch
Then convert that to radians and use that in your CGAffineTransformRotate(). Do that all in your touchesMoved handler.
Here is a function to calculate what you need just that:
static inline CGFloat angleBetweenLinesInRadians(CGPoint line1Start, CGPoint line1End, CGPoint line2Start, CGPoint line2End) {
CGFloat a = line1End.x - line1Start.x;
CGFloat b = line1End.y - line1Start.y;
CGFloat c = line2End.x - line2Start.x;
CGFloat d = line2End.y - line2Start.y;
CGFloat line1Slope = (line1End.y - line1Start.y) / (line1End.x - line1Start.x);
CGFloat line2Slope = (line2End.y - line2Start.y) / (line2End.x - line2Start.x);
CGFloat degs = acosf(((a*c) + (b*d)) / ((sqrt(a*a + b*b)) * (sqrt(c*c + d*d))));
return (line2Slope > line1Slope) ? degs : -degs;
}
Courtesy of Jeff LaMarche at:
http://iphonedevelopment.blogspot.com/2009/12/better-two-finger-rotate-gesture.html
Example:
UITouch *touch = [touches anyObject];
CGPoint origin = [view center];
CGFloat angle = angleBetweenLinesInRadians(origin, [touch previousLocationInView:self.superview.superview], origin, [touch locationInView:self.superview.superview]);
Have you considered using UIRotationGestureRecognizer? Seems like that has the logic already baked in, and might make things simpler.