【发布时间】:2013-03-22 03:33:30
【问题描述】:
我正在尝试在第二个函数 -(void) 加速度计中使用 -(void) awakeaccelerometer 中的 randX 和 randY。程序无法识别它们。提前致谢。
-(void) awakeaccelerometer
{
[[UIAccelerometer sharedAccelerometer]setUpdateInterval:1.0/50.0];
[[UIAccelerometer sharedAccelerometer]setDelegate:self];
float randX = arc4random() % 320;
float randY = arc4random() % 548;
CGPoint randNewPlace = CGPointMake(randX, randY);
Rand.center = randNewPlace;
}
//Controlling the accelerometer
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
.....
CGRect blockRect = CGRectMake(newX, newY, 20, 20);
CGRect targetRect = CGRectMake(randX, randY, 20, 20);
if (CGRectIntersectsRect(blockRect, targetRect))
{
float tnewX = arc4random() % 320;
float tnewY = arc4random() % 548;
CGPoint randNewPl = CGPointMake(tnewX, tnewY);
Rand.center = randNewPl;
}
}
【问题讨论】:
-
忠告:查看braces vs. class definition vs. globals 如何影响变量的范围。
-
这是基本的编程知识,找Objective-C的教程。您正在寻找的是实例变量。
-
所以我的嵌套函数 randX 和 randY 只会使用块作用域中的同名变量,对吗?
-
甚至不需要找到 Objective-C 的教程。 C 或 Java 教程将涵盖这一点。在处理 Objective-C 之前你需要了解的非常基本的东西。
-
所以我将 randY 和 randX 声明为静态变量,然后改为使用它。它可以跟踪第一个放置的坐标,但永远坚持这些坐标。无论如何要返回新坐标的值(tnewX,tnewY)..
标签: objective-c