存档

2011年11月 的存档

uniqueIdentifier deprecated, example from Cocos2d

2011年11月27日 没有评论

I have searched the web for the answer and have found quite a few solutions but have to admit i do not really understand, as i am pretty new, how to apply the answer, one example is: UIDevice uniqueIdentifier Deprecated – What To Do Now?

I would really appreciate if someone could show me an example how to apply the solution to the problem in the code below as the following line is deprecated (uniqueIdentifier), the code line is from Cocos2d CLScoreServerRequest.m but comes up in a few others as well:

device = [[UIDevice currentDevice] uniqueIdentifier];

The function looks like:

-(BOOL) requestScores:(tQueryType)type
            limit:(int)limit
           offset:(int)offset
            flags:(tQueryFlags)flags
         category:(NSString*)category
{
// create the request   
[receivedData setLength:0];

// it's not a call for rank
reqRankOnly = NO;

NSString *device = @"";
if( flags & kQueryFlagByDevice )
    device = [[UIDevice currentDevice] uniqueIdentifier];

// arguments:
//  query: type of query
//  limit: how many scores are being requested. Default is 25. Maximun is 100
//  offset: offset of the scores
//  flags: bring only country scores, world scores, etc.
//  category: string user defined string used to filter
NSString *url= [NSString stringWithFormat:@"%@?gamename=%@&querytype=%d&offset=%d&limit=%d&flags=%d&category=%@&device=%@",
                SCORE_SERVER_REQUEST_URL,
                gameName,
                type,
                offset,
                limit,
                flags,
                [category stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
                device
                ];

//  NSLog(@"%@", url);

NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                   timeoutInterval:10.0];

// create the connection with the request
// and start loading the data
self.connection=[NSURLConnection connectionWithRequest:request delegate:self];
if (! connection_)
    return NO;

return YES;
}

Here’s the quick and simple solution:

Change your project’s (or target’s) deployment target to iOS 4.x or lower. In that case the compiler will still issue a warning but it will be just a warning. Only if your deployment target it iOS 5.0 or newer will the compiler generate an error about the deprecated method.

As for the warnings within the Cocos2D source code, ignore those warnings until the next Cocos2D official release fixes that issue.

you could do:

CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
if(uuidRef)
{
    device = (NSString *) CFUUIDCreateString(kCFAllocatorDefault, uuid);
    CFRelease(uuidRef);
} else {
    // it's almost 100% likely you won't end up here but
    // you should still do something with device (like throw an alert or NSLog)
}

And I just noticed this answer can also be found in this related question.

B.T.W., this UUID will not persist (or be the same) if the app is uninstalled and reinstalled on a device. If you want something like that, you incorporate the code found at:

https://github.com/gekitz/UIDevice-with-UniqueIdentifier-for-iOS-5

Except in this case, there’s apparently a tough license agreement.

分类: stackoverflow精选, unity3d 标签:

How to retrieve absolute position of child sprite (that is child of a parent sprite) in Cocos2d

2011年11月22日 没有评论

I have two parent sprites.

Each parent has two children sprites.

Although the two parent sprites have different positions, it seems that the position of the child sprites for both parents are identical.

What I mean is, although the children are attached to the parent, and visually appear to move wherever the parents move, the point value of the “position” property remains the same.

When you move the parents around the screen, you can see the children moving too. There position really does change.

But the “position” property of the children always remains the same.

What am I doing wrong? How can I retrieve the absolute position of the child sprite?

To get one child’s absolute position, relative to the screen (or more accurately the scene), use this:

CGPoint absolutePosition = [childSprite convertToWorldSpace:childSprite.position];

I don’t think you were doing anything wrong. A child’s position is relative to its parent so it makes sense that the children’s positions are not changing.

分类: cocos2d, stackoverflow精选 标签:

How to determine the collision of a circle with a rectangle? [duplicate]

2011年11月6日 没有评论

This question already has an answer here:

I have looked EVERYWHERE for leads on how to get this to work (nicely) and so far every solution I have come up with has been ugly or didn’t work. What I have is a circular sprite, the enemy. Then I have a sprite that is in the shape of an arrow.

When checking for collision for the arrow in the enemy, I use CGRectIntersect(rect1, rect2)
but… circles are not rectangles! The collision is disgusting.

So my question is, how do I go about checking for collision inside a circular object? Should I make many rects, or is there something out there that is made for this purpose?

Detecting the collision of a circle and a rectangle is anything but simple. Here’s a C++ example class that does this kind of test (source with plenty of other intersection test examples). There’s also an answer on SO that only shows pseudo-code. The N+ developers also explain their approach to circle vs rectangle collision detection. If any of this seems too much for you, you’re hereby advised to look for a simpler approach. ;)

For example, since you mentioned “arrow” that implies a pointed, thin object that tends to fly relatively straight in one direction, with the arrowhead always being pointed in the direction of flight. If that is not the case, I may be have been living on a different planet, otherwise I’ll use this assumption.

It means you can very easily change the collision type of the arrow from rectangle to circle. The circle only needs to be as big so that it encloses the arrowhead. Depending on graphics and your game design it may be even sufficient to have a collision circle at the very tip of the arrowhead. Then you can implement Joshua’s suggestion of circle vs. circle collision tests.

An alternative for very thin arrows would be to assume the arrow to be a line, then you can work with a reasonably simple line-circle intersection test.

I have no idea if Cocos provides a function to do this, but the math is really quite simple.

You take the two center points of the circles, and get the distance between them using your standard distance formula. float distance = sqrt(pow((x2-x1), 2) + pow((y2-y1), 2) and check if that is less than the sum of the radius of the two circles you’re checking.

BOOL checkCircleCollision(CGPoint center1, float radius1, CGPoint center2, float radius2)
{
    float distance = sqrt(pow((center2.x-center1.x), 2) + pow((center2.y-center1.y), 2);
    return distance < (radius1 + radius2);
}

BOOL optimized_CheckCircleCollision(CGPoint center1, float radius1, CGPoint center2, float radius2)
{
    float a = center2.x - center1.x;
    float b = center2.y - center1.y;
    float c = radius1 + radius2;
    float distanceSqrd = (a * a) + (b * b);
    return distanceSqrd < (c * c);
}

I found a very handy page (http://www.migapro.com/circle-and-rotated-rectangle-collision-detection/) with some code and a nice demonstration, and have ported that solution to Objective-C.

when I ported the code, I also altered it such that the coordinate provided within the CGRect is actually the center of the rectangle as opposed to the top-left corner as per the original code. This allows it to be used for Cocos2D objects like CCSprite’s very easily.

The code (which for me seems to work very well) is shown below:

@interface Cocosutil : NSObject

typedef struct {
    float overlapSize;
    BOOL intersects;
} ccIntersection;

+ (ccIntersection) intersectionOfCircleWithRadius:(float)radius 
                                          atPoint:(CGPoint)circlePt
                                     andRectangle:(CGRect)rect
                                     withRotation:(float)rotation;

@end

@implementation CocosUtil

#define CC_DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) * 0.01745329252f) // PI / 180

// Original code is from:
//
// http://www.migapro.com/circle-and-rotated-rectangle-collision-detection/
//
+ (ccIntersection) intersectionOfCircleWithRadius:(float)radius atPoint:(CGPoint)circlePt andRectangle:(CGRect)rect withRotation:(float)rotation {
    ccIntersection result;

    // Rotate circle's center point back
    float unrotatedCircleX =
        cosf(CC_DEGREES_TO_RADIANS(rotation)) * (circlePt.x - rect.origin.x) -
        sinf(CC_DEGREES_TO_RADIANS(rotation)) * (circlePt.y - rect.origin.y) + rect.origin.x;

    float unrotatedCircleY =
        sinf(CC_DEGREES_TO_RADIANS(rotation)) * (circlePt.x - rect.origin.x) +
        cosf(CC_DEGREES_TO_RADIANS(rotation)) * (circlePt.y - rect.origin.y) + rect.origin.y;

    // Closest point in the rectangle to the center of circle rotated backwards(unrotated)
    float closestX, closestY;

    // Find the unrotated closest x point from center of unrotated circle
    if (unrotatedCircleX  < (rect.origin.x - (rect.size.width/2.0f))) {
        closestX = rect.origin.x - (rect.size.width/2.0f);
    } else if (unrotatedCircleX  > rect.origin.x + (rect.size.width+rect.size.width/2.0f)) {
        closestX = rect.origin.x + (rect.size.width/2.0f);
    } else {
        closestX = unrotatedCircleX ;
    }

    // Find the unrotated closest y point from center of unrotated circle
    if (unrotatedCircleY < (rect.origin.y - (rect.size.height/2.0f))) {
        closestY = rect.origin.y - (rect.size.height/2.0f);
    } else if (unrotatedCircleY > (rect.origin.y + (rect.size.height/2.0f))) {
        closestY = rect.origin.y + (rect.size.height/2.0f);
    } else {
        closestY = unrotatedCircleY;
    }

    // Determine collision

    float distance = [CocosUtil distanceFrom:CGPointMake(unrotatedCircleX , unrotatedCircleY) to:CGPointMake(closestX, closestY)];

    if (distance < radius) {
        result.intersects = YES; // Collision
        result.overlapSize = radius - distance;
    } else {
        result.intersects = NO;
        result.overlapSize = 0.0f;
    }

    return result;
}

+ (float) distanceFrom:(CGPoint)from to:(CGPoint)to {

    float a = abs(from.x - to.x);
    float b = abs(from.y - to.y);

    return sqrt((a * a) + (b * b));
}

@end
分类: cocos2d, stackoverflow精选 标签:

Screen coordinate systems for armv6, armv7 (IPhone development)

2011年11月2日 没有评论

I am writing a game for the iPhone/iPodTouch (using Cocos2d) and I have noticed something strange…

I need to detect the parts of the screen which the player touches in order to perform certain actions.

For example:

-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint touchLocation = [touch locationInView:[touch view]];    
//DEBUG
CCLOG(@"Button pressed: X Location: %f",touchLocation.x);
CCLOG(@"Button pressed: Y Location: %f",touchLocation.y);


And when touchLocation.x and touchLocation.y are both within a certain range, I do something.

It worked on the simulator fine. When I compiled it for my test device, using armv7 architecture (optimized) it also worked. But when I compiled it with armv6, armv7 architectures enabled (which is what the app store requires), I noticed that the code no longer worked. The CCLOGs showed me that the X,Y coordinate system used when I compiled for armv6,armv7 was DIFFERENT to that used when I only compiled for armv7 (optimized).

How can I get around this problem? Is the only way to use the coordinate system used by armv6,armv7 when testing on the device… (this doesn’t work on the simulator)? There is no way I can upload an app for the iPhone and compile only for armv7 (optimized). :(

For finding touches on screen in cocos2d, Try this code. Its working correctly in my game app

- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    UITouch *myTouch = [touches anyObject];
    CGPoint location = [myTouch locationInView:[myTouch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
}
分类: stackoverflow精选, unity3d 标签: