我正在尝试使用UISnapBehavior
创建tweening back
动画。
我试图制作一个正方形可拖动,然后当正方形被释放时,它会回到原来的位置。每次它回补,它似乎有一个奇怪的轨迹,而不是在正确的角度缓和回来似乎在到达目的地之前在一个奇怪的半圆中缓和。
提前谢谢。
我的代码如下:
var animator:UIDynamicAnimator? = nil;
var ball : Ball!;
var ball2 : Ball!;
var snap: UISnapBehavior!
var gravity : UIGravityBehavior!;
var speed : Double! = 0;
var lastTouchPoint : CGPoint!;
var attach : UIAttachmentBehavior! = nil;
var itemBehavior : UIDynamicItemBehavior!;
var snapping : UISnapBehavior! = nil;
var currentBall : Ball! = nil;
override init(frame: CGRect) {
super.init(frame: frame);
println( "-- initiated view --" );
self.backgroundColor = UIColor.orangeColor();
ball = Ball( frame: CGRect(x: 200, y: 200, width: 50, height: 50 ) );
self.addSubview(ball);
ball2 = Ball( frame: CGRect(x: 100, y: 100, width: 50, height: 50 ) );
self.addSubview(ball2);
setup()
self.addGestureRecognizer( UIPanGestureRecognizer(target: self, action: "panHandler:") );
self.attach = UIAttachmentBehavior(item: self, attachedToAnchor: CGPoint(x: 0, y: 0) );
}
func setup() {
animator = UIDynamicAnimator(referenceView:self);
var collision: UICollisionBehavior!
collision = UICollisionBehavior(items: [ball, ball2])
collision.translatesReferenceBoundsIntoBoundary = false;
collision.collisionDelegate = self;
animator?.addBehavior(collision)
var dynamicItem : UIDynamicItemBehavior = UIDynamicItemBehavior(items: [ball, ball2] );
dynamicItem.allowsRotation = false;
self.animator!.addBehavior(dynamicItem);
}
func panHandler( recognizr : UIPanGestureRecognizer ) {
switch( recognizr.state ) {
case UIGestureRecognizerState.Began:
let location = recognizr.locationInView(self);
let view : AnyObject? = self.hitTest(location, withEvent: nil);
if( view is Ball ) {
currentBall = view as! Ball;
if( self.attach != nil ){ self.animator!.removeBehavior(attach); self.attach = nil; }
self.attach = UIAttachmentBehavior(item: currentBall, attachedToAnchor: location );
self.animator!.addBehavior(self.attach);
self.attach.damping = 1;
self.attach.length = 1;
let dynamicItem : UIDynamicItemBehavior = UIDynamicItemBehavior(items: [currentBall] );
dynamicItem.allowsRotation = false;
self.animator!.addBehavior(dynamicItem);
}
break;
case UIGestureRecognizerState.Changed :
if( currentBall != nil ) {
let location = recognizr.locationInView(self);
self.attach.anchorPoint = location;
}
break;
default :
println("--- snap ---");
if( self.currentBall == nil ) {return;}
self.animator!.removeBehavior(attach);
self.attach = nil;
var snap : UISnapBehavior = UISnapBehavior(item: self.currentBall, snapToPoint: self.currentBall.startingPoint );
snap.damping = 1;
self.animator!.addBehavior(snap);
break;
}
}