一開始沒有做過真的還不知道怎麼下手..像是flash可以用hitTest來偵測碰撞
果然iphone也有一個hitTest 不過..那是用來偵測使用者touch
在沒有頭緒的情況下就去請教google 翻了許多文章後找到了一些方法
好像是如果要做遊戲的話 還是建議使用cocos2d
而我這邊只是簡單的偵測碰撞 所以我利用iphone內建的function
還有一個別人寫的function 實在是非常厲害阿!
CGRectIntersectsRect
可以用來偵測CGRect的碰撞,只是偵測範圍是矩形
if( CGRectIntersectsRect(objA.frame, objB.frame) ){
NSLog(@"Collision!");
}
另一個是將要被偵測碰撞的圖片 解析透明的地方
然後透過function去偵測point 也就可以不規則形狀的碰撞
-(void) initCollisionMap:(UIImage *)image {
/** Pixel collision detetction initialization **/
//1) Load the image:
UIImage *collisionImage = [image retain];
//2) Get the image size:
int width = (int)collisionImage.size.width;
int height = (int)collisionImage.size.height;
//3) Allocate our array for quick lookups and clear it:
collisionMap = (unsigned char *)malloc( width * height );
memset( collisionMap, 0, width * height );
//4) Get access to the raw bits of the image
CFDataRef imageData = CGDataProviderCopyData( CGImageGetDataProvider
( collisionImage.CGImage ) );
const UInt32 *pixels = (const UInt32*)CFDataGetBytePtr( imageData );
//5) Build our collision map:
for(int j = 0; j < (width * height); j++ )
if ( pixels[j] & 0xff000000 ) collisionMap[j] |= 1;
//6) Release what we no longer need:
CFRelease( imageData );
}
-(int)collisionForPoint:(CGPoint)point
{
int x = (int)point.x;
int y = (int)point.y;
// TODO: check for boundaries here
return collisionMap[(y*480)+x] ;
}
順便附上使用重力陀螺儀(UIAccelerometer)的使用
//開始啟用重力偵測
//偵測的頻率:10Hz to 100Hz.
[UIAccelerometer sharedAccelerometer].updateInterval = 1/30;
[UIAccelerometer sharedAccelerometer].delegate = self;
#pragma mark UIAccelerometerDelgate
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
//do something
}
//關閉
[UIAccelerometer sharedAccelerometer].delegate = nil;
參考資料
http://snipplr.com/view/54886
http://homepages.ius.edu/rwisman/C490/html/chapter22.htm

0 意見:
張貼留言