OpenGL +处理:根据方向旋转和移动

Pat*_*ick 2 java opengl processing geometry

我正在尝试旋转并根据三角形的指向方向将三角形移动到某个方向.理论上,我计算方向的正弦和余弦(0-360度)并将这些值加到x和y位置,对吗?它只是不起作用.

此外,三角形应该指向开头,而不是向下.

public void speedUp() {
  float dirX, dirY;
  speed *= acceleration;
  if(speed > 50) speed = 50;
  println("dir: " + direction + " x: " + cos(direction) + " y: " + sin(direction));
  dirX = cos(direction);
  dirY = sin(direction);
  xPos+=dirX;
  yPos+=dirY;
}

public void redraw() {
  GL gl = pgl.beginGL();  // always use the GL object returned by beginGL
  gl.glTranslatef(xPos, yPos, 0);
  gl.glRotatef(direction, 0, 0, 1000);

  gl.glBegin(GL.GL_TRIANGLES);
  gl.glColor4f(0.1, 0.9, 0.7, 0.8);
  gl.glVertex3f(-10, -10, 0);    // lower left vertex
  gl.glVertex3f( 10, -10, 0);    // lower right vertex
  gl.glVertex3f( 0,  15, 0);    // upper vertex
  gl.glEnd();
}
Run Code Online (Sandbox Code Playgroud)

Kos*_*Kos 5

你的单位搞砸了.glRotatef除了度数和三角函数期望弧度.这是最明显的错误.


此外,speed从未在您的代码段中使用过.我想你以某种方式使用它的每一帧,但在你粘贴的代码中:

xPos+=dirX

这基本上是"增加位置的方向" - 没有多大意义,除非你想"在speedUp()调用的那一刻"将它在给定的方向上正好移动一个单位.持续移动的通常方法是:

// each frame:
xPos += dirX * speed * deltaTime;
yPos += dirY * speed * deltaTime;
Run Code Online (Sandbox Code Playgroud)


Geo*_*nza 5

看起来你需要从极坐标(使用角度和半径移动)转换为笛卡尔坐标(使用x和y移动).

该公式看起来有点像这样:

x = cos(angle) * radius;
y = sin(angle) * radius;
Run Code Online (Sandbox Code Playgroud)

因此,正如@Lie Ryan所提到的,你还需要乘以速度(这是你在极坐标中的半径).

要么你的角度是度,但是使用cos,sin时使用弧度(),使用弧度时使用sin,或者使用弧度,使用度数()glRotatef,直到你

另外,您可能需要查看glPushMatrix()和glPopMatrix().基本上,它们允许您嵌套转换.无论您使用块进行何种转换,它们都会在本地影响该块.

这就是我的意思,使用w,a,s,d键:

import processing.opengl.*;
import javax.media.opengl.*;

float direction = 0;//angle in degrees
float speed = 0;//radius
float xPos,yPos;

void setup() {
  size(600, 500, OPENGL);
}

void keyPressed(){
  if(key == 'w') speed += 1;
  if(key == 'a') direction -= 10;
  if(key == 'd') direction += 10;
  if(key == 's') speed -= 1;
  if(speed > 10) speed = 10;
  if(speed < 0) speed = 0;
  println("direction: " + direction + " speed: " + speed);
}

void draw() {
  //update
  xPos += cos(radians(direction)) * speed;
  yPos += sin(radians(direction)) * speed;
  //draw
  background(255);
  PGraphicsOpenGL pgl = (PGraphicsOpenGL) g; 
  GL gl = pgl.beginGL();
  gl.glTranslatef(width * .5,height * .5,0);//start from center, not top left

  gl.glPushMatrix();
  {//enter local/relative
    gl.glTranslatef(xPos,yPos,0);
    gl.glRotatef(direction-90,0,0,1);
    gl.glColor3f(.75, 0, 0);
    gl.glBegin(GL.GL_TRIANGLES);
    gl.glVertex2i(0, 10);
    gl.glVertex2i(-10, -10);
    gl.glVertex2i(10, -10);
    gl.glEnd();
  }//exit local, back to global/absolute coords
  gl.glPopMatrix();

  pgl.endGL();
}
Run Code Online (Sandbox Code Playgroud)

你实际上并不需要{}用于推送和弹出矩阵调用,我将它们添加为视觉辅助.此外,您可以通过连接变换来实现此操作而无需推/弹,但是在您需要时可以方便地知道它们是适合您的.当你想要从那个三角形中射出一些GL_LINES时,可能会派上用场... pew pew pew!

HTH