//
//  ViewController.m
//  ex_UIDA_Snap
//
//  Created by yoshiyuki oshige on 2013/10/05.
//  Copyright (c) 2013年 yoshiyuki. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    CGFloat offsetRx, offsetRy;
    CGFloat offsetLx, offsetLy;
}
// カエルの身体と左右の目玉
@property (weak, nonatomic) IBOutlet UIImageView *body;
@property (weak, nonatomic) IBOutlet UIImageView *eyeR;
@property (weak, nonatomic) IBOutlet UIImageView *eyeL;
// アニメータとビヘイビア
@property (nonatomic, strong) UIDynamicAnimator *animator;
@property (nonatomic, strong) UISnapBehavior *bodySnapBehavior;
@property (nonatomic, strong) UISnapBehavior *rightEyeSnapBehavior;
@property (nonatomic, strong) UISnapBehavior *leftEyeSnapBehavior;
// タップで実行するメソッド
- (IBAction)tappedView:(UITapGestureRecognizer *)sender;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // アニメータを作る
	self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
    // 身体と目の距離を保存しておく
    offsetRx = _eyeR.center.x - _body.center.x;
    offsetRy = _eyeR.center.y - _body.center.y;
    offsetLx = _eyeL.center.x - _body.center.x;
    offsetLy = _eyeL.center.y - _body.center.y;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// ビューのタップでアニメーション
- (IBAction)tappedView:(UITapGestureRecognizer *)sender {
    //タップした座標から移動先を決める
    CGPoint tapPoint = [sender locationInView:self.view];
    CGPoint eyeRpoint = CGPointMake(tapPoint.x+offsetRx, tapPoint.y+offsetRy);
    CGPoint eyeLpoint = CGPointMake(tapPoint.x+offsetLx, tapPoint.y+offsetLy);
    
    // 登録済みのスナップビヘイビアをアニメータから消去する
    [self.animator removeBehavior:self.bodySnapBehavior];
    [self.animator removeBehavior:self.rightEyeSnapBehavior];
    [self.animator removeBehavior:self.leftEyeSnapBehavior];
    // 新しいスナップビヘイビアを作る
    self.bodySnapBehavior = [[UISnapBehavior alloc] initWithItem:_body snapToPoint:tapPoint];
    self.rightEyeSnapBehavior = [[UISnapBehavior alloc] initWithItem:_eyeR snapToPoint:eyeRpoint];
    self.leftEyeSnapBehavior = [[UISnapBehavior alloc] initWithItem:_eyeL snapToPoint:eyeLpoint];
    // アニメータにスナップビヘイビアを登録する
    [self.animator addBehavior:self.bodySnapBehavior];
    [self.animator addBehavior:self.rightEyeSnapBehavior];
    [self.animator addBehavior:self.leftEyeSnapBehavior];

}
@end
