我在屏幕底部有一个图层(字符),另一层(食物)从屏幕顶部掉落。我的目标是让食物层能够在动画期间检测它与角色的交叉点,但是我很难搞清楚它。
这是我目前的代码,任何帮助都将非常感谢:
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!");
}
答案 0 :(得分:0)
这应该让你开始。
声明属性:
@property (strong, nonatomic) CALayer *food;
@property (strong, nonatomic) CALayer *character;
@property (strong, nonatomic) NSTimer *timer;
添加以下方法:
我添加了用于测试目的的图层:
- (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];
}
}
然后致电 :
[self prepareLayersAndAnimation];
代码已经过测试。希望这可以帮助。