所以这是我遇到问题的程序部分的代码。我的目标是让炮塔旋转,但我需要它在坦克的轴上旋转它,这样它的运动看起来很自然。我不知道该怎么做,我尝试过的一切都不起作用,所以我只需要知道从哪里开始。并且给出了computeGradient函数,因此我必须使用它来确定如何更改炮塔的x和y位置。任何帮助是极大的赞赏。
#include <fstream>
#include <iostream>
#include <string>
#include "engine.h"
#include "constants.h"
using namespace std;
void initTankState(float& tankX, float& tankY, float& turretX, float& turretY, int& tankAngle, int& turretAngle){
tankX = SCREEN_WIDTH/2;
tankY = SCREEN_HEIGHT*.75;
turretX = tankX;
turretY = tankY;
tankAngle = 0;
turretAngle = 0;
}
void loadInfantryData(string path, int& numInfantry, float*& infantryPosX, float*& infantryPosY, int*& infantryAngle){
fstream fin;
fin.open(path, ios::in);
fin>>numInfantry;
for (int i = 0; i<numInfantry; i++)
{
fin>>infantryPosX[i]>>infantryPosY[i]>>infantryAngle[i];
}
}
void changeGameState(string command, float& tankX, float& tankY, float& turretX, float& turretY, int & tankAngle, int & turretAngle, int numInfantry, float* infantryPosX, float* infantryPosY, int* infantryAngle){
float x;
float y;
computeGradient(x, y, tankAngle);
/*if (command == "up")
moveForward(tankX, tankY, tankAngle);
else if (command =="down")
moveBackward(tankX, tankY, tankAngle);
else*/ if (command == "left")
turnLeft(tankX, tankY, tankAngle);
else if (command == "right")
turnRight(tankX, tankY, tankAngle);
else if (command == "pleft")
{
panLeft(turretAngle);
turretX = x;
turretY = y;
}
else if (command == "pright")
{
panRight(turretAngle);
turretX = x;
turretY = y;
}
}
void updateTurret(float, float, float&, float&, int, int)
{
}
void panLeft(int &turretAngle) //here
{
turretAngle++;
if (turretAngle <0)
turretAngle = TANK_NUM_SPRITES-1;
if (turretAngle >TANK_NUM_SPRITES-1)
turretAngle = 0;
}
void panRight(int &turretAngle) //and here are where I've run into a block
{
turretAngle--;
if (turretAngle >TANK_NUM_SPRITES-1)
turretAngle = 0;
if (turretAngle <0)
turretAngle = TANK_NUM_SPRITES-1;
}
void moveForward(float &, float &, int &, float)
{
}
void moveBackward(float &, float &, int &, float)
{
}
void turnLeft(float &tankX, float &tankY, int &tankAngle)
{
tankAngle++;
if (tankAngle <0)
tankAngle = TANK_NUM_SPRITES-1;
if (tankAngle >TANK_NUM_SPRITES-1)
tankAngle = 0;
}
void turnRight(float &tankX, float &tankY, int &tankAngle)
{
tankAngle--;
if (tankAngle <0)
tankAngle = TANK_NUM_SPRITES-1;
if (tankAngle >TANK_NUM_SPRITES-1)
tankAngle = 0;
}
void noAction(float &, float &, int &)
{
}
//Trigonometric Calculation
void computeGradient(float & dx, float & dy, int tankAngle){
int tmpAngle = ( (TANK_NUM_SPRITES-tankAngle))%TANK_NUM_SPRITES;
float radianAngle=(2*PI)*(float(tmpAngle)/TANK_NUM_SPRITES)-(PI/2.0);
dx = cos(radianAngle);
dy = sin(radianAngle);
}
答案 0 :(得分:1)
我不建议使用/信任你不理解的功能,除非你绝对必须这样做。我建议学习computeGradients背后的数学,这可以在线获得。我的线性代数是生锈的,所以我不能用trig来帮助太多。我认为它归结为跟踪坦克的位置,方向和正确的向量,以及水平和垂直角度。数学类似于here.
所描述的数学从我记忆中,你必须将坦克翻译成世界空间的原点,应用线性变换矩阵(在这种情况下是旋转),然后将其转换回它的位置(我不知道是否computeGradients那含蓄地)。这是基于我对OpenGL中模型矩阵如何工作的有限知识。
无论如何,我希望我所说的任何帮助。