[英]OpenGL - Why doesn't my ball move?
在OpenGL中,我正在構建一個足球游戲,該游戲允許您先通過左右移動高度指示器來射擊球,然后再根據按下按鈕時的指示器進行射擊。 看起來是這樣的:
當這些指示器移動時,我的球需要在垂直指示器(y)的高度移動,並且如果垂直指示器(x)則向左或向右移動。
首先,這是移動指標的代碼(只是在RenderScene()
函數中繪制的紋理)
void SpecialKeys(int key, int x, int y){
if (key == GLUT_KEY_RIGHT) { // moves the bottom indicator RIGHT
horizontalBarX += 5.0f;
}
if (key == GLUT_KEY_LEFT) {
horizontalBarX -= 5.0f; // moves the bottom indicator LEFT
}
if (key == GLUT_KEY_UP) { // moves the top indicator UP
verticalBarY += 5.0f;
verticalBarX += 1.0f;
}
if (key == GLUT_KEY_DOWN) { // moves the top indicator DOWN
verticalBarY -= 5.0f;
verticalBarX -= 1.0f;
}
}
我的足球運動的計算
現在,要讓我的足球在指示器移動之后移動,我需要對球的x
, y
和z
軸應用以下計算:
x = sin(θ)* cos(phi)y = cos(theta)* sin(phi)z = cos(theta)
其中theta = zx的角度,phi = zy的角度
因此,我嘗試首先根據您在SpecialKeys()
函數中按下的高度指示符簡單地增加它們的角度,從而首先獲取theta和phi角度的值:
void SpecialKeys(int key, int x, int y){
if (key == GLUT_KEY_RIGHT) { // moves the bottom indicator RIGHT
horizontalBarX += 5.0f;
theta += 5; // Increase theta angle by 5
}
if (key == GLUT_KEY_LEFT) {
horizontalBarX -= 5.0f; // moves the bottom indicator LEFT
theta -= 5; // Decrease theta angle by 5
}
if (key == GLUT_KEY_UP) { // moves the top indicator UP
verticalBarY += 5.0f;
verticalBarX += 1.0f;
phi += 5; // Increase theta angle by 5
}
if (key == GLUT_KEY_DOWN) { // moves the top indicator DOWN
verticalBarY -= 5.0f;
verticalBarX -= 1.0f;
phi -= 5; // Decrease phi angle by 5
}
}
現在我有了角度,我想將計算出的值插入到drawFootball()參數中,順便說一下,在我的RenderScene函數中,該參數最初被稱為...
drawFootBall(0, 40, 500, 50); // x,.y, z, r
...這就是我根據上述計算方法嘗試發射的方式:
void SpecialKeys(int key, int x, int y){
// indicator if statements just above this line
if (key == GLUT_KEY_F1) {
drawFootBall(sin(theta)*cos(phi), cos(theta)*sin(phi), cos(theta), 50);
}
}
但是當我單擊啟動按鈕F1時 , 什么也沒有發生 。 我在哪里搞砸了?
編輯:
如果有幫助,這是我的drawFootball()
函數:
void drawFootBall(GLfloat x, GLfloat y, GLfloat z, GLfloat r)
{
glPushMatrix();
glFrontFace(GL_CCW);
glTranslatef(x,y,z);
//create ball texture
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textures[TEXTURE_BALL]);
//glDisable(GL_LIGHTING);
glColor3f(0.5,0.5,0.5);
quadricFootball = gluNewQuadric();
gluQuadricDrawStyle(quadricFootball, GLU_FILL);
gluQuadricNormals(quadricFootball, GLU_SMOOTH);
gluQuadricOrientation(quadricFootball, GLU_OUTSIDE);
gluQuadricTexture(quadricFootball, GL_TRUE);
gluSphere(quadricFootball, r, 85, 50);
glDisable(GL_TEXTURE_2D);
glPopMatrix();
}
首先確保您的theta
和phi
處於正確的單位,即弧度。 如果以度為單位,則通過使用sin(theta * PI/180.0f)
等將其轉換為弧度,並假設PI已定義。
我相信您正在計算的是球的方向向量。 d(x,y,z)
是球應該運動的方向(假設沒有重力或其他力)。 它可能是球踢的方向。
我認為,如果您只是想移動球,則需要將該方向乘以一個長度。 由於您的球的半徑為50個單位,請嘗試轉換為該半徑的2倍。
glTranslatef(2.0f*r*x,2.0f*r*y,2.0f*r*z);
這會將球沿您想要的方向移動到其半徑的2倍。 但是,您可能需要一些物理學來使運動更逼真。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.