質問

I have a layer (character) at the bottom of the screen and another layer (food) being dropped from the top of the screen. My goal is to give the food layer the ability to detect when it intersects with the character during animation but I am having a tough time figuring it out.

Here is my current code and any help would be great appreciated:

CABasicAnimation *drop = [CABasicAnimation animationWithKeyPath:@"position"];

[drop setDelegate:self];

[drop setFromValue:[NSValue valueWithCGPoint:[food position]]];

float bottomx = [food position].x;
float bottomy = [character position].y;

newPosition = CGPointMake(bottomx, bottomy);

[drop setToValue:[NSValue valueWithCGPoint:(newPosition)]];

[drop setDuration:2.0];

[food addAnimation:drop forKey:@"drop"];

[food setPosition:newPosition];


if (CGRectIntersectsRect(food.frame, character.frame)){
    NSLog(@"They touched!");

}
役に立ちましたか?

解決

This should get you started.

Declare properties:

@property (strong, nonatomic) CALayer *food;
@property (strong, nonatomic) CALayer *character;
@property (strong, nonatomic) NSTimer *timer;

Add following methods:

I added layers for testing purpose:

- (void)prepareLayersAndAnimation
{
    self.food = [CALayer layer];
    CGPoint newPosition;
    self.food.backgroundColor = [[UIColor greenColor] CGColor];
    self.food.frame = (CGRect){{160, 300}, 45, 45};

    self.character = [CALayer layer];
    self.character.frame = (CGRect){{160, 50}, 45, 45};
    self.character.backgroundColor = [[UIColor blueColor] CGColor];

    [self.view.layer addSublayer:self.food];
    [self.view.layer addSublayer:self.character];

    CABasicAnimation *drop = [CABasicAnimation animationWithKeyPath:@"position"];
    [drop setDelegate:self];
    [drop setFromValue:[NSValue valueWithCGPoint:[self.food position]]];

    float bottomx = [self.food position].x;
    float bottomy = [self.character position].y;
    newPosition = CGPointMake(bottomx, bottomy);
    [drop setToValue:[NSValue valueWithCGPoint:(newPosition)]];
    [drop setDuration:2.0];
    [self.food addAnimation:drop forKey:@"drop"];
    [self.food setPosition:newPosition];
}

- (void)animationDidStart:(CAAnimation *)anim
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(detectCollision) userInfo:nil repeats:YES];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    [self.timer invalidate];
}

- (void)detectCollision
{
    if (CGRectIntersectsRect([[self.food presentationLayer] frame] , self.character.frame))
    {
        NSLog(@"They touched!");
        [self.timer invalidate];
    }
}

Then call:

[self prepareLayersAndAnimation];

Code is tested. Hope this helps.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top