我正在尝试一些简单的动画,并遵循了基本弹跳球的教程。
如何使用我自己的一组坐标而不是整个屏幕来限制球弹跳的位置?我在教程中使用的代码从整个屏幕中随机选取坐标,我想设置它的坐标,以便它只在屏幕中间的一个小方 block 中弹跳,而不是出去这些界限。
.m
int ballx, bally;
///////
ballx = arc4random() % 320;
bally = arc4random() % 480;
//////////
-(void)movetheball {
[UIView beginAnimations: @"MovingTheBallAround" context: nil];
[UIView setAnimationDelegate: self];
[UIView setAnimationDuration: 1.0];
[UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
myball.frame = CGRectMake(ballx, bally,myball.frame.size.width,myball.frame.size.height);
[UIView commitAnimations];
}
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(SEL)aSelector {
if (finished) {
// set new coordinate for ballx and bally
ballx = arc4random() % 320;
bally = arc4random() % 480;
[self movetheball];
}
我看过SO,但我找不到任何类似的东西,除了以下内容:
ballx.center = CGPointMake(320/2, [self randNumBetween:-50:-100]);
我尝试去适应它,但没有取得多大成功。我没有丰富的编程经验,所以我不确定我的代码是否偏离了基础
最佳答案
ballx = arc4random() % 320;
bally = arc4random() % 480;
正如您所注意到的,这些是您设置球的新坐标的行,并且这两个变量只是数字。它们没有名为 center
的组件,也不是 CGPoint
,因此,尽管您的建议修改是正确的,但您却让事情变得太复杂了为你自己。
你可能不理解的部分是%
符号;这是"modulus"运算符(operator)。简单来说,就是限制其左边的数字小于右边的数字。
请注意,320
和 480
恰好是整个屏幕的宽度和高度,并观察您正在分配模运算的结果 - 使用它宽度和高度——代表球位置的变量。
希望这已经足够了。
关于objective-c - 限制动画球在屏幕上的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11368270/