在我的游戏中,我有一个头文件,其中包含游戏中季节的属性和函数。这些属性都是静态的,包括一个代表当前季节的浮点和另一个代表季节之间过渡中当前点的浮点,如果不转换则为零。
整个游戏中的几个功能都依赖于转换(此时有两个),其中一个功能运行良好。不过,在另一种情况下,这根本不起作用。
在负责控制游戏背景的类中,每当引用“SeasonTransition”变量时,它都会出现零。但在另一个类中,以完全相同的方式引用变量,它会得出实际值。
这是游戏更新几帧后调用断点后的图片:
这些变量再次在 C 头文件中声明:
#import "somestuff.h"
static float SeasonTransition
etc...
这不应该是这样做的吗?我该如何解决这个问题?
编辑:
Season.h文件如下:
//GL.h contains different functions and global variables to be used anywhere in the project.
//This file, like Season.h is a singular header file with static declarations, and is setup
//the same way. I have been developing this from the start of the project and havent had any
//problems with it.
#import "GL.h"
static float currentSeason;
static float SeasonTransition;
static void UpdateSeason(){
currentSeason += 0.0002f;
float TransitionLength = 0.15f;
float SeasonDepth = Clamp(currentSeason - floorf(currentSeason), 0, TransitionLength);
float bigTL = TransitionLength / 4;
float endTL = TransitionLength;
float Speed2 = 0;
float Speed1 = 1;
float bRatio = SeasonDepth / bigTL;
float eRatio = SeasonDepth / endTL;
SeasonTransition = (SeasonDepth < TransitionLength) ?
((SeasonDepth < bigTL) ?
(Speed1 * bRatio) + (Speed2 * (1.0f - bRatio)) :
(Speed1 * (1.0f - eRatio)) + (Speed2 * eRatio))
:
Speed2;
}
最佳答案
如果将 static float SeasonTransition;
放入两个单独的 C 文件中(或两个单独的 C 文件包含一个头文件),则每个 C 文件都会有自己的 < em>变量的独立副本。
如果这些 C 文件之一随后修改了该变量,它将修改其副本。它不会触及另一个 C 文件中的文件。这听起来像你现在的情况。
执行此操作的正常方法是在一个变量中定义变量并在另一个变量中将其声明为外部变量,如下所示:
file1.c:
int myVar; // it exists here.
file2.c:
extern int myVar; // it exists, but elsewhere.
您不想在第一个中将其标记为static
,因为这实际上会使它对第二个不可见。然后您在第二个中将其标记为 extern
,以便它知道该变量存在于其他地方(在第一个中)。
如果它不是静态的,您实际上会看到效果。当链接器将这两个文件链接在一起时,它会提示有两个变量具有相同的名称。
如何做到这一点有很多变体,我展示了最简单的一个。最好有这样的东西:
file1.h:
extern int myVar; // so everyone knows about the variable
// just by including this.
file1.c:
#include "file1.h" // or import for ObjC.
int myVar; // the actual variable.
file2.c:
#include "file1.h" // now we know about it, in the OTHER C file.
关于objective-c - 当 float 不为零时,则将其视为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12291878/