我希望能够在按下手指时取出初始点,然后取出手指释放时的点,并获得两者之间的线(角度)并让球继续沿着该路径行进。我写了一些代码,但是当我尝试时,球似乎在所有不同的方向上都会出现。
for(Ball *balls in self.view.subviews){
[UIView beginAnimations:nil context:nil];
//[UIView setAnimationRepeatAutoreverses:NO];
CGFloat x;
CGFloat y;
for(Ball *subBalls in self.view.subviews){
if(balls != subBalls)
if((CGRectIntersectsRect([balls frame], [subBalls frame]))){
[subBalls changeDirectionX];
[subBalls changeDirectionY];
}
}
CGPoint point = balls.center;
if(point.x + 25 > self.view.bounds.size.width)
[balls changeDirectionX];
if(point.x - 25 < 0)
[balls changeDirectionX];
if(point.y + 25 > self.view.bounds.size.height)
[balls changeDirectionY];
if(point.y - 25 < 0)
[balls changeDirectionY];
if(balls.directionX == 1){
x = point.x + (balls.speed * cos(balls.addx));
}
else{
x = point.x - (balls.speed * cos(balls.addx));
//balls.addx;
}
if(balls.directionY == 1){
y = point.y + (balls.speed * sin(balls.addx));
}
else
y = point.y - (balls.speed * sin(balls.addx));
//balls.addy;
//CGFloat x = (CGFloat) random()/(CGFloat) RAND_MAX * self.view.bounds.size.width;
//CGFloat y = (CGFloat) random()/(CGFloat) RAND_MAX * self.view.bounds.size.height;
CGPoint squarePostion = CGPointMake(x, y);
balls.center = squarePostion;
[UIView commitAnimations];
这是我尝试计算角度的地方
-(void) dragging:(UIPanGestureRecognizer *)p{
UIView *v = p.view;
CGPoint velocity;
if(p.state == UIGestureRecognizerStateBegan){
self.origC = v.center;
self.pointIn = [p locationInView:[UIApplication sharedApplication].keyWindow];
//NSLog(@"%f",self.pointIn.x);
//pointInWindow = CGPointMake(pointIn.x, pointIn.y);
}
//NSLog(@"%f,%f orig %f, %f",pointInWindow.x, pointInWindow.y,self.origC.x,self.origC.y);
velocity = [p velocityInView:v.superview];
//NSLog(@"x=%f",velocity.x);
//NSLog(@"y=%f",velocity.y);
[UIView animateWithDuration:1 delay:0 options:UIViewAnimationCurveEaseInOut animations:^{
CGPoint delta = [p translationInView:v.superview];
CGPoint c = self.origC;
c.x += delta.x;
c.y += delta.y;
v.center = c;
}completion:nil];
if(p.state == UIGestureRecognizerStateEnded){
CGPoint lastPoint = [p locationInView:[UIApplication sharedApplication].keyWindow];
NSLog(@"lastpoint.x: %f, lastpoint.y: %f, pointin.x: %f, pointin.y%f",lastPoint.x,lastPoint.y,
self.pointIn.x,self.pointIn.y);
double velocityX = velocity.x;
double velocityY = velocity.y;
if(velocityX > velocityY)
self.speed = velocityX/200;
else
self.speed = velocityY/200;
//NSLog(@"orig %f , last %f",self.pointIn.x,lastPoint.x);
self.lateC = v.center;
CGFloat deltaX = lastPoint.x - self.pointIn.x;
CGFloat deltaY = lastPoint.y - self.pointIn.y;;
//NSLog(@"deltaX: %f, deltaY: %f ",deltaX,deltaY);
double angle = atan(deltaY/deltaX) * 180/M_PI;
if(angle < 0)
angle += 360;
NSLog(@"angle: %f",angle);
self.addy = angle;
self.addx = angle;
self.timer = [NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(changeVelocity) userInfo:nil repeats:YES];
}
}
感谢您的帮助