2016-02-05 33 views
0

所以我一直在使用google搜索,並瀏覽各種資源 - 文本,講座等 - 但我要麼丟失了某些東西,要麼沒有正確掌握它。對於OpenGL中的一個課程,我們需要設計一個Asteroids遊戲,這個遊戲似乎是一個足夠簡單的概念,但是我發現很難讓我的船的移動正確。我知道我們需要將我們的船翻譯成原點,執行旋轉並將其翻譯回適當的位置 - 我面臨的問題是理解它的執行。我有畫船的代碼是這個至今:OpenGL - 旋轉2D小行星運輸工具

void 
drawShip(Ship *s) 
{ 
    glClear(GL_COLOR_BUFFER_BIT); 


    glMatrixMode(GL_MODELVIEW); 
    glLoadIdentity(); 
    glPushMatrix(); 
    myTranslate2D(s->x, s->y); 
    float x = s->x, y = s->y; 
    myRotate2D(s->phi); 
    glBegin(GL_LINE_LOOP); 
    glVertex2f(s->x + s->dx, s->y + s->dy + 3); 
    glVertex2f(s->x + s->dx-2, s->y + s->dy - 3); 
    glVertex2f(s->x + s->dx, s->y + s->dy -1.5); 
    glVertex2f(s->x + s->dx + 2, s->y + s->dy - 3); 
    glEnd(); 
    myTranslate2D(s->x - x, s->y - y); 
    glPopMatrix(); 
} 

被以下變量,這些變量在鍵盤功能修改正確確定的旋轉和運動:

if (left == 1) 
    { 
     ship.phi -= 0.3; 
    } 
    if (right == 1) 
    { 
     ship.phi += 0.3; 
    } 
    if (up == 1) 
    { 
     ship.dx += -2.0*sin(ship.phi); 
     ship.dy += 2.0*cos(ship.phi); 
    } 
    if (down == 1) 
    { 
     ship.dx += 2.0*sin(ship.phi); 
     ship.dy += -2.0*cos(ship.phi); 
    } 
    drawShip(&ship); 

一旦我得到的輪換下來,我相信我可以完成所有工作的其餘部分。實際上,上面的代碼將允許我的對象在原點或其周圍旋轉,但除非它直接位於原點,否則它不會在原地旋轉。船本身已經被初始化爲(0,0),(25,25)和(50,50)的點,並且爲了我的目的,屏幕的原點(0,0)是左下角。

有人可以幫助我理解爲什麼我的船不會在原地旋轉,只有原點?我期望這與我如何執行我的翻譯和輪換有關,但我對此感到不知所措。

+0

看起來像C.不要爲C語言添加C++標籤,它們是不同的語言! – Olaf

回答

1

您的繪圖函數看起來不對。 您的船舶設計不應該依賴於它的位置。這意味着頂點的座標應始終相同。然後使用GlTranslate和Rotate將其置於正確的位置。繪製完之後,在彈出矩陣之前,您還會進行翻譯。這並不會做任何事情,因爲矩陣更改僅適用於矩陣更改後定義的頂點。

的結構應該是這樣的:

// Make sure the origin is in the 0, 0 of your space. 
GlPushMatrix(); // Save this setup 
GlTranslate(ship.x, ship.y); // Location of the ship. 
GlRotate(ship.phi); // Or whatever is the name of the angle of the ship. 

DrawShip(); // Draws the sprite/wireframe/object you want. 
GlPopMatrix(); // Return to the original setup. 
+0

謝謝,這實際上指出了我的正確道路!你所展示的實際上是我正在做的事情,但有一點需要注意,我在線路循環本身中進行了奇怪的修改。非常感謝! – JonMcDev

1

好吧,我確實有些戳了它。問題在於我直接從繪圖中繪製速度變化,而不是根據速度計算新位置並翻譯。這裏是固定的代碼:

glClear(GL_COLOR_BUFFER_BIT); 
    glMatrixMode(GL_MODELVIEW); 
    glLoadIdentity(); 
    glPushMatrix(); 
    float newX = s->x + s->dx, newY = s->y + s->dy; 
    myTranslate2D(newX, newY); 
    myRotate2D(s->phi); 
    glBegin(GL_LINE_LOOP); 
    glVertex2f(s->x, s->y + 3); 
    glVertex2f(s->x - 2, s->y - 3); 
    glVertex2f(s->x, s->y - 1.5); 
    glVertex2f(s->x + 2, s->y - 3); 
    glEnd(); 
    glPopMatrix();