how to do smooth movement of sprites in cocos2d - iphone

In my cocos2d project I am moving sprites from left most corner to the right most corner using CCMoveBy action. here is the code
CCSprite* sprite1 = [CCSprite spriteWithFile:#"Icon.png"];
sprite1.position = ccp(100, 100);
[self addChild:sprite1];
[sprite1 runAction:[CCSequence actions:
[CCMoveBy actionWithDuration:4 position:ccp(300, 0)],
[CCMoveBy actionWithDuration:2 position:ccp(0, 200)],
[CCMoveBy actionWithDuration:4 position:ccp(-300, 0)],
[CCMoveBy actionWithDuration:2 position:ccp(0, -200)], nil]];
the sprite is not moving smoothly, instead it stuck sometimes while moving.
someone asked a similar question In cocos2d forum
http://www.cocos2d-iphone.org/forums/topic/ccactions-not-running-smoothly-specifically-ccmoveby-and-ccrotateby/
but In my game I am using action sequences at so many places and it would be too much to code every movement sequence by scheduling update or custom selectors.

i think you can achieve this by following code
MovingSprite.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#interface MovingSprite : CCSprite {
float _vx;
float _vy;
}
-(void) update:(ccTime)dt;
#property (nonatomic, assign) float vx;
#property (nonatomic, assign) float vy;
#end
MovingSprite.m
#import "MovingSprite.h"
#implementation MovingSprite
#synthesize vx = _vx;
#synthesize vy = _vy;
-(void)update:(ccTime)dT
{
self.vy -= (kGravity * dT); //optionally apply gravity
self.position = ccp(self.position.x + (self.vx*dT), self.position.y + (self.vy*dT));
}
And add [self scheduleUpdate]; to the init method of your game layer. Then add an update method within the game layer where you call update for all moving sprites.

Related

Trying to implement radial gravity with Cocos2d 2.X

I am trying to learn how to implement radial gravity to specific objects and I was using the tutorial on (http://www.vellios.com/2010/06/11/radial-gravity-w-box2d-source/), but this tutorial is written an older version of Cocos2d. I have tried to fixed it as much as I could. If someone can point me in the right direction, i would really appreciate. Here is what I have so far. I commented the places that I am having problems with. Thank you.
HelloWorldLayer.h
#import <GameKit/GameKit.h>
// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"
#import "Box2D.h"
#import "GLES-Render.h"
#define PTM_RATIO 32
// HelloWorldLayer
#interface HelloWorldLayer : CCLayer <GKAchievementViewControllerDelegate, GKLeaderboardViewControllerDelegate>
{
b2World* world; // strong ref
GLESDebugDraw *m_debugDraw; // strong ref
}
// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;
#end
HelloWorldLayer.mm
// Import the interfaces
#import "HelloWorldLayer.h"
// Needed to obtain the Navigation Controller
#import "AppDelegate.h"
#define PTM_RATIO 32
#define kRADIAL_GRAVITY_FORCE 250.0f
enum {
kTagParentNode = 1,
kTagTileMap = 1,
kTagSpriteSheet = 1,
kTagAnimation1 = 1,
};
#pragma mark - HelloWorldLayer
#interface HelloWorldLayer()
-(void) initPhysics;
-(void) addNewSpriteAtPosition:(CGPoint)p;
-(void) createMenu;
#end
#implementation HelloWorldLayer
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(id) init
{
if( (self=[super init])) {
// enable events
self.isTouchEnabled = YES;
self.isAccelerometerEnabled = YES;
CGSize screenSize = [CCDirector sharedDirector].winSize;
CCLOG(#"Screen width %0.2f screen height %0.2f",screenSize.width,screenSize.height);
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
// This will speed up the physics simulation
bool doSleep = true;
// Construct a world object, which will hold and simulate the rigid bodies.
world = new b2World(gravity);
world->SetAllowSleeping(doSleep);
world->SetContinuousPhysics(true);
//Set up sprite
CCSprite *sheet = [CCSprite spriteWithFile:#"blocks.png"];
[self addChild:sheet z:0 tag:kTagSpriteSheet];
[self addNewSpriteAtPosition:ccp(screenSize.width/2, screenSize.height/2)];
//ERROR Use of undeclared identifier 'CCLabel'
//ERROR Use of undeclared identifier 'label'
CCLabel *label = [CCLabel labelWithString:#"Tap Screen" fontName:#"Marker Felt" fontSize:32];
// ERROR Use of undeclared identifier 'label'
[self addChild:label z:0];
//ERROR Use of undeclared identifier 'label'
[label setColor:ccc3(0,0,255)];
//ERROR Use of undeclared identifier 'label'
label.position = ccp( screenSize.width/2, screenSize.height-50);
// Create our static "Planet" - Nick
b2CircleShape shape;
shape.m_radius = 1.0f;
shape.m_p.Set(8.0f, 8.0f);
b2FixtureDef fd;
fd.shape = &shape;
//ERROR Use of undeclared identifier 'planet'
planet = groundBody->CreateFixture(&fd);
// End Create Planet - Nick
[self schedule: #selector(tick:)];
// init physics
[self initPhysics];
[self scheduleUpdate];
}
return self;
}
-(void) dealloc
{
delete world;
world = NULL;
delete m_debugDraw;
m_debugDraw = NULL;
[super dealloc];
}
-(void) createMenu
{
}
-(void) initPhysics
{
CGSize s = [[CCDirector sharedDirector] winSize];
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
world = new b2World(gravity);
// Do we want to let bodies sleep?
world->SetAllowSleeping(true);
world->SetContinuousPhysics(true);
// Debug Draw functions
m_debugDraw = new GLESDebugDraw( PTM_RATIO );
world->SetDebugDraw(m_debugDraw);
uint32 flags = 0;
flags += b2Draw::e_shapeBit;
// flags += b2Draw::e_jointBit;
// flags += b2Draw::e_aabbBit;
// flags += b2Draw::e_pairBit;
// flags += b2Draw::e_centerOfMassBit;
m_debugDraw->SetFlags(flags);
// Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0); // bottom-left corner
// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
b2Body* groundBody = world->CreateBody(&groundBodyDef);
// Define the ground box shape.
b2EdgeShape groundBox;
// bottom
groundBox.Set(b2Vec2(0,0), b2Vec2(s.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
// top
groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox,0);
// left
groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(0,0));
groundBody->CreateFixture(&groundBox,0);
// right
groundBox.Set(b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
}
-(void) draw
{
//
// IMPORTANT:
// This is only for debug purposes
// It is recommend to disable it
//
[super draw];
// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
// Needed states: GL_VERTEX_ARRAY,
// Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
glDisable(GL_TEXTURE_2D);
glDisable(GL_COLOR_BUFFER_BIT);
world->DrawDebugData();
}
-(void) addNewSpriteAtPosition:(CGPoint)p
{
CCLOG(#"Add sprite %0.2f x %02.f",p.x,p.y);
CCSprite *sheet = (CCSprite*) [self getChildByTag:kTagSpriteSheet];
int idx = (CCRANDOM_0_1() > .5 ? 0:1);
int idy = (CCRANDOM_0_1() > .5 ? 0:1);
//ERROR Cannot initialize a parameter of type 'CCTexture2D *' with an lvalue of type 'CCSprite *'
CCSprite *sprite = [CCSprite spriteWithTexture:sheet rect:CGRectMake(32 * idx,32 * idy,32,32)];
[sheet addChild:sprite];
sprite.position = ccp( p.x, p.y);
// Define the dynamic body.
//Set up a 1m squared box in the physics world
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
bodyDef.userData = sprite;
b2Body *body = world->CreateBody(&bodyDef);
// Define another box shape for our dynamic body.
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box
// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body->CreateFixture(&fixtureDef);
}
-(void) update: (ccTime) dt
{
//It is recommended that a fixed time step is used with Box2D for stability
//of the simulation, however, we are using a variable time step here.
//You need to make an informed choice, the following URL is useful
//http://gafferongames.com/game-physics/fix-your-timestep/
int32 velocityIterations = 8;
int32 positionIterations = 1;
// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);
//Iterate over the bodies in the physics world
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
b2Body* ground = planet->GetBody();
b2CircleShape* circle = (b2CircleShape*)planet->GetShape();
// Get position of our "Planet" - Nick
b2Vec2 center = ground->GetWorldPoint(circle->m_p);
// Get position of our current body in the iteration - Nick
b2Vec2 position = b->GetPosition();
// Get the distance between the two objects. - Nick
b2Vec2 d = center - position;
// The further away the objects are, the weaker the gravitational force is - Nick
float force = kRADIAL_GRAVITY_FORCE / d.LengthSquared(); // 150 can be changed to adjust the amount of force - Nick
d.Normalize();
b2Vec2 F = force * d;
// Finally apply a force on the body in the direction of the "Planet" - Nick
b->ApplyForce(F, position);
if (b->GetUserData() != NULL) {
//Synchronize the AtlasSprites position and rotation with the corresponding body
CCSprite *myActor = (CCSprite*)b->GetUserData();
myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//Add a new body/atlas sprite at the touched location
for( UITouch *touch in touches ) {
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
[self addNewSpriteAtPosition:location];
}
}
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
static float prevX=0, prevY=0;
//#define kFilterFactor 0.05f
#define kFilterFactor 1.0f // don't use filter. the code is here just as an example
float accelX = (float) acceleration.x * kFilterFactor + (1- kFilterFactor)*prevX;
float accelY = (float) acceleration.y * kFilterFactor + (1- kFilterFactor)*prevY;
prevX = accelX;
prevY = accelY;
// accelerometer values are in "Portrait" mode. Change them to Landscape left
// multiply the gravity by 10
b2Vec2 gravity( -accelY * 10, accelX * 10);
world->SetGravity( gravity );
}
#pragma mark GameKit delegate
-(void) achievementViewControllerDidFinish:(GKAchievementViewController *)viewController
{
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] dismissModalViewControllerAnimated:YES];
}
-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] dismissModalViewControllerAnimated:YES];
}
#end

graphic context of rotated layers ignores any transformations

I'm composing a view by several layers, some of them rotated. The display of these layers works perfectly, however when I try to make an image, all rotations/transformations are ignored.
For example if I have a CALayer containing an image of an arrow pointing to the left, after a rotation around the z axis (using CATransform3DMakeRotation) it points to the top, and the layer is correctly displayed. However if I get an image of this layer (using renderInContext), the arrow still points to the left, ignoring any transformations.
Anyone any idea why, and what do I have to do to get my wanted result? :-)
Example code:
// ViewController.m
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
// Don't forget to add the QuartzCore framework to your target.
#interface ViewController ()
#end
#implementation ViewController
- (void)loadView {
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.view.backgroundColor = [UIColor lightGrayColor];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Get the arrow image (tip to the left, 50 x 50 pixels).
// (Download the image from here: http://www.4shared.com/photo/uQfor7vC/arrow.html )
UIImage *arrowImage = [UIImage imageNamed:#"arrow"];
// The arrow layer in it's starting orientation (tip to the left).
CGRect layerFrame = CGRectMake(50.0, 50.0, arrowImage.size.width, arrowImage.size.height);
CALayer *arrowLayerStart = [CALayer new];
arrowLayerStart.frame = layerFrame;
[arrowLayerStart setContents:(id)[arrowImage CGImage]];
[self.view.layer addSublayer:arrowLayerStart];
// The arrow layer rotated around the z axis by 90 degrees.
layerFrame.origin = CGPointMake(layerFrame.origin.x + layerFrame.size.width + 25.0, layerFrame.origin.y);
CALayer *arrowLayerZ90 = [CALayer new];
arrowLayerZ90.frame = layerFrame;
[arrowLayerZ90 setContents:(id)[arrowImage CGImage]];
arrowLayerZ90.transform = CATransform3DMakeRotation(M_PI/2.0, 0.0, 0.0, 1.0);
[self.view.layer addSublayer:arrowLayerZ90];
// Now make images of each of these layers and display them in a second row.
// The starting layer without any rotation.
UIGraphicsBeginImageContext(arrowLayerStart.frame.size);
[arrowLayerStart renderInContext:UIGraphicsGetCurrentContext()];
UIImage *arrowStartImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
layerFrame.origin = CGPointMake(arrowLayerStart.frame.origin.x,
arrowLayerStart.frame.origin.y + arrowLayerStart.frame.size.height + 25.0);
CALayer *arrowLayerStartCaptured = [CALayer new];
arrowLayerStartCaptured.frame = layerFrame;
[arrowLayerStartCaptured setContents:(id)[arrowStartImage CGImage]];
[self.view.layer addSublayer:arrowLayerStartCaptured];
// The second layer, rotated around the z axis by 90 degrees.
UIGraphicsBeginImageContext(arrowLayerZ90.frame.size);
[arrowLayerZ90 renderInContext:UIGraphicsGetCurrentContext()];
UIImage *arrowZ90Image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
layerFrame.origin = CGPointMake(arrowLayerZ90.frame.origin.x,
arrowLayerZ90.frame.origin.y + arrowLayerZ90.frame.size.height + 25.0);
CALayer *arrowLayerZ90Captured = [CALayer new];
arrowLayerZ90Captured.frame = layerFrame;
[arrowLayerZ90Captured setContents:(id)[arrowZ90Image CGImage]];
[self.view.layer addSublayer:arrowLayerZ90Captured];
}
#end
// ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#end
// AppDelegate.h
#import <UIKit/UIKit.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#end
// AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#implementation AppDelegate
#synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = [[ViewController alloc] init];
[self.window makeKeyAndVisible];
return YES;
}
#end
The documentation for -[CALayer renderInContext:] says:
The Mac OS X v10.5 implementation of this method does not
support the entire Core Animation composition model.
QCCompositionLayer, CAOpenGLLayer, and QTMovieLayer layers are not
rendered. Additionally, layers that use 3D transforms are not
rendered, nor are layers that specify backgroundFilters, filters,
compositingFilter, or a mask values. Future versions of Mac OS X may
add support for rendering these layers and properties.
(This limitation is present on iOS, too.)
The header CALayer.h also says:
* WARNING: currently this method does not implement the full
* CoreAnimation composition model, use with caution. */
Essentially, -renderInContext: is useful in a few simple cases, but will not work as expected in more complicated situations. You will need to find some other way to do your drawing. Quartz (Core Graphics) will work for 2D, but for 3D you're on your own.
You can use Core Graphaic instead of CATransform3DMakeRotation :)
CGAffineTransform flip = CGAffineTransformMakeScale(1.0, -1.0);

Rotate a sprite in cocos2d using accelerometer

I'm on cocos2d and I have a sprite that I would like to rotate with the accelerometer.
I've heard about CMMotionManager. I would like to know if it is possible to use it just for 2D rotation, and, if yes, how?
put this in onEnter:
UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
accelerometer.updateInterval = 1.0/50.0; //update interval in sec...so 1/50= 20 ms
accelerometer.delegate = self;
you need to conform to UIAccelerometerDelegate like so:
#interface MyClass:CCLayer <UIAccelerometerDelegate>
and implement this in MyClass.m:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
CCLOG(#"x = %f y = %f z = %f",acceleration.x,acceleration.y,acceleration.z);
mysprite.rotation=acceleration.x*20;
}
edit: almost forgot...put accelerometer.delegate = nil; in onExit
note that the method is called every time the accelerometer changes value..in all 3 vectors
cards on the table..i didnt use accelerometer ...ever..but it should look something like this...check the rotation property in the documentation and play a little with it
hope it helps
PS: loved the "sorry for my english i'm french" part...hilarious
edit: here is my test of that code..and made a few modifications..it works fairly smooth..if you dont like it play around with the values.
#import "cocos2d.h"
// HelloWorldLayer
UIAccelerationValue accelerationX;
UIAccelerationValue accelerationY;
float currentRawReading;
float calibrationOffset;
#interface HelloWorldLayer : CCLayer <UIAccelerometerDelegate>
{
CCLabelTTF *label;
}
// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;
#end
#import "HelloWorldLayer.h"
// HelloWorldLayer implementation
#implementation HelloWorldLayer
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
#define kFilteringFactor .05
CGFloat RadiansToDegrees(CGFloat radians) {return radians *180/M_PI;};
// on "init" you need to initialize your instance
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {
UIAccelerometer *accel= [UIAccelerometer sharedAccelerometer];
accel.delegate=self;
accel.updateInterval=1/60;
// create and initialize a Label
label = [CCLabelTTF labelWithString:#"Hello World" fontName:#"Marker Felt" fontSize:64];
// ask director the the window size
CGSize size = [[CCDirector sharedDirector] winSize];
// position the label on the center of the screen
label.position = ccp( size.width /2 , size.height/2 );
label.flipY=YES; //i have absolutly no idea why the label is fliped :/
label.flipX=YES;
label.rotation=0;
// add the label as a child to this Layer
[self addChild: label];
}
return self;
}
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
CCLOG(#"acc called");
accelerationX=acceleration.x *kFilteringFactor +accelerationX *(1-kFilteringFactor);
accelerationY=acceleration.y*kFilteringFactor +accelerationY *(1-kFilteringFactor);
currentRawReading=atan2(accelerationY, accelerationX);
label.rotation=-RadiansToDegrees(currentRawReading);
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
// in case you have something to dealloc, do it in this method
// in this particular example nothing needs to be released.
// cocos2d will automatically release all the children (Label)
// don't forget to call "super dealloc"
[super dealloc];
}
#end

Passing position and color of square to UIView subview

I work on a project for iPhone iOS4 with Xcode.
From MainViewController I want to draw a little red square (fill only, not stroke) in MyView, a subclass of UIView. How can I pass position and RGB color of the square?
MyView.h (subclass of UIView)
#interface {
CGPoint position; // OK
CGFloat[3] color; // ???
}
#property CGPoint position; // OK
#property CGFloat color; // ???
MyView.m
#synthesize position; // OK
#synthesize color; // ???
MainViewController.h
MyView *myRect;
property IBOutlet MyView *myRect;
MainViewController.m
#synthesize myRect;
- (void) viewDidLoad
myRect.position = CGPointMake (0, 0); // OK
myRect.color = CGFloat [] = {255, 0, 0, 1} // ???
I think I have no problems with the position of the square. But how can I pass the color of the square?
Thank you.
[myRect setBackgroundColor:[UIColor colorWithRed:color[0] green:color[1] blue:color[2] alpha:1.0]];

Determine if MKOverlay contains a CLLocationCoordinate2D (or MKMapPoint) [duplicate]

I'm trying to calculate if a specific annotation(like the blue circle of the user location) or a MKPinAnnotation is inside an MKPolygon layer on the mapview.
Any advice to achieve this?
The following converts the coordinate to a CGPoint in the polygon view and uses CGPathContainsPoint to test if that point is in the path (which may be non-rectangular):
CLLocationCoordinate2D mapCoordinate = ...; //user location or annot coord
MKMapPoint mapPoint = MKMapPointForCoordinate(mapCoordinate);
MKPolygonView *polygonView =
(MKPolygonView *)[mapView viewForOverlay:polygonOverlay];
CGPoint polygonViewPoint = [polygonView pointForMapPoint:mapPoint];
BOOL mapCoordinateIsInPolygon =
CGPathContainsPoint(polygonView.path, NULL, polygonViewPoint, NO);
This should work with any overlay view that is a subclass of MKOverlayPathView. You can actually replace MKPolygonView with MKOverlayPathView in the example.
Slightly modified above to do calculations for points/coordinates in polygons without the use of a MKMapView formatted as an extension to MKPolygon class:
//MKPolygon+PointInPolygon.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MKPolygon (PointInPolygon)
-(BOOL)coordInPolygon:(CLLocationCoordinate2D)coord;
-(BOOL)pointInPolygon:(MKMapPoint)point;
#end
//MKPolygon+PointInPolygon.m
#import "MKPolygon+PointInPolygon.h"
#implementation MKPolygon (PointInPolygon)
-(BOOL)coordInPolygon:(CLLocationCoordinate2D)coord {
MKMapPoint mapPoint = MKMapPointForCoordinate(coord);
return [self pointInPolygon:mapPoint];
}
-(BOOL)pointInPolygon:(MKMapPoint)mapPoint {
MKPolygonRenderer *polygonRenderer = [[MKPolygonRenderer alloc] initWithPolygon:self];
CGPoint polygonViewPoint = [polygonRenderer pointForMapPoint:mapPoint];
return CGPathContainsPoint(polygonRenderer.path, NULL, polygonViewPoint, NO);
}
#end
Enjoy!