i want to jump balls in a specific field in the view, the problem i开发者_运维知识库s that i don't know how to define the positions of this field area and movement. also here is the code that i use to move the ball in the entire view (the ball object is a uiimageview on the view). thanks.
-(void) onTimer { ball.center = CGPointMake(ball.center.x+pos.x,ball.center.y+pos.y);
if(ball.center.x > 320 || ball.center.x < 0)
pos.x = -pos.x;
if(ball.center.y > 460 || ball.center.y < 0)
pos.y = -pos.y;
}
// Implement viewDidLoad to do additional setup after loading the view. - (void)viewDidLoad { pos = CGPointMake(14.0,7.0);
[NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
Instead of hard-coding 320 and 460, you can use the bounds of the view to get the are in which your balls should move.
Check out the bounds
property of UIView
.
@implementation ViewController {
BOOL isPositiveXAxis;
BOOL isPositiveYAxis;
}
- (void)viewDidLoad {
[super viewDidLoad];
//By default we are setting both BOOL value to YES because ballImage have (0,0) origin by default
isPositiveXAxis = YES;
isPositiveYAxis = YES;
imgBallView.layer.cornerRadius = imgBallView.frame.size.width/2;
[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(animateBall) userInfo:nil repeats:YES];
}
-(void)animateBall {
//getting current image transform, and we will modify it later in code
CGAffineTransform transform = imgBallView.transform;
//checking if ‘isPositiveXAxis is true and imgBallView xAxis have less value then view border
if (isPositiveXAxis && imgBallView.frame.origin.x < self.view.frame.size.width - imgBallView.frame.size.width) {
transform.tx++;
}
else {
isPositiveXAxis = NO;
if (transform.tx>0) {
transform.tx--;
}
else {
isPositiveXAxis = YES;
}
}
//checking if ‘isPositiveYAxis is true and imgBallView yAxis have less value then view border
if (isPositiveYAxis && imgBallView.frame.origin.y < self.view.frame.size.height - imgBallView.frame.size.height) {
transform.ty++;
}
else {
isPositiveYAxis = NO;
if (transform.ty>0) {
transform.ty--;
}
else {
isPositiveYAxis = YES;
}
}
//setting updated trasform to imgBallView it will look animated.
imgBallView.transform = transform;
}
The above code will generate the required pattern. It can be seen in the video: https://vid.me/G3zO, which may help you understand it better
精彩评论