標籤:
一,重力與碰撞
//建立物理模擬器
UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
self.animator = animator; //強引用animator,否則代碼塊執行完成後,將被釋放
//建立重力行為
UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[self.view1]];
//設定一些屬性(可以不設定,不設則都為預設)
gravityBehavior.gravityDirection = CGVectorMake(0, 1); //重力方向
gravityBehavior.angle = M_PI*0.5; //重力方向
gravityBehavior.magnitude = 0.5; //重力加速度,1代表加速度是(每秒100個點)
//把重力行為行為添加到模擬器
[animator addBehavior:gravityBehavior];
//建立碰撞行為
UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[self.view1,self.view2]];
//設定碰撞邊界,不設定就會飛出螢幕,設定就會在螢幕邊框處產生碰撞效果
collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
//將碰撞行為加入物理模擬器
[animator addBehavior:collisionBehavior];
二,捕捉行為
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //擷取觸摸點 UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:touch.view]; //建立模擬模擬器 UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view]; self.animator = animator; //模擬器 //建立捕捉行為 UISnapBehavior *snapBehavior = [[UISnapBehavior alloc] initWithItem:self.redView snapToPoint:point]; //設定反彈係數(反彈幅度越大,值越大,反彈幅度越小) snapBehavior.damping = 0.5; //將行為添加到模擬器 [animator addBehavior:snapBehavior]; }
iOS 物理方面