我想在视图中的特定字段中跳球, 问题是我不知道如何定义这个领域和运动的位置。 也 这是我用来在整个视图中移动球的代码(球对象是视图上的uiimageview)。 感谢。
- (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;
}
//在加载视图后实现viewDidLoad以进行其他设置。 - (void)viewDidLoad { pos = CGPointMake(14.0,7.0);
[NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
答案 0 :(得分:0)
您可以使用视图的边界来获取球应该移动的位置,而不是硬编码320和460.
查看bounds
的{{1}}属性。
答案 1 :(得分:0)
@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;
}
上面的代码将生成所需的模式。可以在视频中看到:https://vid.me/G3zO,这可以帮助您更好地理解