以下两个函数计算obj类型对象的体力。第一个函数调用第二个函数两次,有没有办法将这些方法组合在一起?
void calculateBodyForcesForEach(obj *pBody, obj *pHead, sys *sys) {
float fTotalForce[4] = {0.0f};
calculateBodyForces(pBody, sys->m_pSun, fTotalForce, sys);
for (obj *pOtherBody = pHead; pOtherBody;) {
if (pBody != pOtherBody) {
calculateBodyForces(pBody, pOtherBody, fTotalForce, sys);
}
pOtherBody = pOtherBody->m_pNext;
}
vecCopy(fTotalForce, pBody->m_fForce);
}
void calculateBodyForces(obj *pBody, obj *pOtherBody,
float *fTotalForce, solarSystem *sys)
{
pBody->m_fForce[0] = 0.0f;
pBody->m_fForce[1] = 0.0f;
pBody->m_fForce[2] = 0.0f;
float fCalculatedForce[3] = {0.0f};
float fCalculatedMass = pBody->m_fMass * pOtherBody->m_fMass;
float fDistanceBetweenPos[3] = {0.0f};
vecSub(pOtherBody->m_fPosition, pBody->m_fPosition, fDistanceBetweenPos);
float fDistanceSquared = (fDistanceBetweenPos[0] * fDistanceBetweenPos[0]) + (fDistanceBetweenPos[1] * fDistanceBetweenPos[1]) + (fDistanceBetweenPos[2] * fDistanceBetweenPos[2]);
float fUnitVector[3] = {0.0f};
vecSub(pOtherBody->m_fPosition, pBody->m_fPosition, fUnitVector);
vecNormalise(fUnitVector, fUnitVector);
float fGravitationalForce = sys->m_fGravitationalConstant * (fCalculatedMass / fDistanceSquared);
vecScalarProduct(fUnitVector, fGravitationalForce, fCalculatedForce);
vecAdd(fTotalForce, fCalculatedForce, fTotalForce);
}
//////到目前为止我的解决方案但仍无效
void calculateVelocityAndPosition(planet *pElement, solarSystem *pSystem) { //completly modified
float fStartPosition[4] = {0.0f,0.0f,0.0f,0.0f};
float fAccelerationTime[3] = {0.0f,0.0f,0.0f};
float fVelocityInterval[3] = {0.0f,0.0f,0.0f};
float fTotalCalculated[3] = {0.0f,0.0f,0.0f};
vecCopy(pElement->m_fPosition, fStartPosition);
vecScalarProduct(pElement->m_fAcceleration, pSystem->m_fTimeStep * pSystem->m_fTimeStep, fAccelerationTime);
vecScalarProduct(fAccelerationTime, 0.5f, fAccelerationTime);
vecScalarProduct(pElement->m_fVelocity, pSystem->m_fTimeStep, fVelocityInterval);
vecAdd(fVelocityInterval, fAccelerationTime, fTotalCalculated);
vecAdd(fStartPosition, fTotalCalculated, pElement->m_fPosition);
fori(3){
pElement->m_fVelocity[i] = (pElement->m_fPosition[i] - fStartPosition[i]) / pSystem->m_fTimeStep;
}
fori(3)
if (pElement->m_fVelocity[i] > pSystem->m_fMaxVelocity)
pElement->m_fVelocity[i] = pSystem->m_fMaxVelocity;
else if (pElement->m_fVelocity[i] < pSystem->m_fMaxNegativeVelocity)
pElement->m_fVelocity[i] = pSystem->m_fMaxNegativeVelocity;
vecScalarProduct(pElement->m_fVelocity, pSystem->m_fDragCoefficient, pElement->m_fVelocity);
}
答案 0 :(得分:0)
fori(3)
这是什么意思?
这笔款项:
float fDistanceSquared = (fDistanceBetweenPos[0] * fDistanceBetweenPos[0]) + (fDistanceBetweenPos[1] * fDistanceBetweenPos[1]) + (fDistanceBetweenPos[2] * fDistanceBetweenPos[2]);
更好地制作一个循环:
float fDistanceSquared = 0.0f
for (int i = 0; i<3; i++)
fDistanceSquared += fDistanceBetweenPos[i] * fDistanceBetweenPos[i];
您如何确定标量产品?为什么有三个变量? 此外,了解正在解决的问题可能会有所帮助。