gpt4 book ai didi

java - OpenGL + 处理 : Rotate and move based on direction

转载 作者:行者123 更新时间:2023-12-02 06:15:33 26 4
gpt4 key购买 nike

我正在尝试根据三角形的指向方向旋转并将三角形移动到某个方向。理论上,我计算方向(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();
}

最佳答案

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

公式看起来有点像这样:

x = cos(angle) * radius;
y = sin(angle) * radius;

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

要么以度为单位的角度,但在使用 cos,sin 时使用 radians(),因为它们与弧度一起使用,或者使用弧度,并使用 Degrees() 与 < strong>glRotatef,由你决定

此外,您可能想看看 glPushMatrix() 和 glPopMatrix()。基本上,它们允许您嵌套转换。无论您对 block 进行什么转换,它们都只会影响本地 block 。

这就是我的意思,使用 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();
}

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

HTH

关于java - OpenGL + 处理 : Rotate and move based on direction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4237867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com