September 19, 2009 3

Throwing an object

By admin in Uncategorized

This is how you throw an object, or at least how I chose to do it coming from an AS background.
You’ll need two pieces information for this, which are where the touches started and where they are when they end. 

So go ahead and make a property in the header file.

@interface HelloWorld : Layer
{
	CGPoint _lastTouchPoint;
}
@property(nonatomic) CGPoint _lastTouchPoint;

You’ll notice I’m extending Layer, that’s because I’m using the Cocos2D framework.

Now you’ll need two functions in the implementation file, one for touchesBegan and one for touchesEnded.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-(BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch *touch = [touches anyObject];
	if(touch)
	{
 
		CGPoint location = [touch locationInView: [touch view]];
		CGPoint relativePoint = [[Director sharedDirector] convertCoordinate:location];
 
		_lastTouchPoint = relativePoint;
 
		return YES;
	}
	else
		return NO;
}

First thing we want to do, is grab the location. Secondly we convert it to our Cocos2D coordinates by calling the proper function in Director (kind of like Stage in AS3).

Now we use that data to figure out our angle

- (BOOL) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch *touch = [touches anyObject];
	if(touch)
	{
		CGPoint location = [touch locationInView: [touch view]];
		CGPoint relativePoint = [[Director sharedDirector] convertCoordinate:location];
 
		int maxDistance = 120; // How far back we care about being pulled
                int maxForce = 100; // Max strength to apply
 
		CGFloat distance = ccpDistance(_lastTouchPoint, relativePoint);
		if(distance > maxDistance) distance = maxDistance; // If it's greater, just clamp it at this
		CGFloat strength = distance / maxDistance;
		CGFloat angle = atan2f(_lastTouchPoint.y - relativePoint.y, _lastTouchPoint.x - relativePoint.x);
 
		int force = strength * maxForce;
                CGPoint velocity = ccp(cosf(angle) * force, sinf(angle) * force);
 
		return YES;
	}
	else {
		return NO;
	}
 
	return YES;
}

That’s kind of about it, then you use that velocity in your own update function however you would like.

Tags:

3 Responses to “Throwing an object”

  1. Lapa says:

    Hi,

    you should add more information about what you do exactly… Like your are going to throw an object by following the movement of the finger.

  2. SMK says:

    Dear, have any source project about the code? regards

  3. Uwe says:

    Hi, thank you for sharing the snippets. Could you please put them together as a small projects that shows how to get it used?

    Thanks!

Leave a Reply

Powered by WP Hashcash

Spam protection by WP Captcha-Free