单摆运动模拟实现异常求助:代码逻辑问题排查
单摆运动模拟异常问题排查请求
我正在学习实现单摆运动模拟,初始代码先施加重力,计算参考点到受重力影响后的端点向量,通过点积求解参考向量与变化向量的夹角,再以此角度设置摆锤位置,但运行结果异常。参考可汗学院相关文档修改代码后仍未解决问题,附上初始代码、修改后代码及异常效果动图,请求排查问题所在。
异常效果

初始代码
void SinglePendulum::setPendulum(double dt) { // Apply gravity auto acc = acceleration; Vec3<double> gravity(0.0, -9.8, 0.0); // x = 0.0, y = -9.8, z = 0.0 acc += gravity * inverseMass; // get accelation velocity += acc * dt; // get velocity velocity *= pow(dampingCoeff, dt); // apply damping variablePosition += velocity * dt; // gravity-affected weight // Vector from reference point to end point after being affected by gravity variableVector = variablePosition - pivotPosition; // a Position - b Position : b->a vector // The angle between the reference vector and the current vector double angle; angle = standardVector.Dot(variableVector); // dot product the reference vector and the variable vector double standVecLength = standardVector.Length(); // magnitude of reference vector double variaVecLength = variableVector.Length(); // magnitude of variable vector double finalAngle = acos(angle / (standVecLength * variaVecLength)); // get angle // Apply position with pendulum motion changePos.Set(sin(finalAngle) * length, cos(finalAngle) * length, 0.0); // apply x, y, z value }
修改后代码
void SinglePendulum::setPendulum(double dt) { // The angle between the reference vector and the current vector double theta; theta = standardVector.Dot(variableVector); // dot product the reference vector and the variable vector double standVecLength = standardVector.Length(); // magnitude of reference vector double variaVecLength = variableVector.Length(); // magnitude of variable vector double angle = acos(theta / (standVecLength * variaVecLength)); // get angle Vec3<double> gravity(0.0, -9.8, 0.0); // x = 0.0, y = -9.8, z = 0.0 Vec3<double> forceX; Vec3<double> forceY; forceX.SetX(-9.8 * sin(angle)); // x = -9.8 * sin(angle), y = 0.0, z = 0.0 forceY.SetY(-9.8 * cos(angle)); // x = 0.0, y = -9.8 * cos(angle), z = 0.0 // Apply gravity auto acc = acceleration; acc += gravity * inverseMass; // get accelation acc += forceX; acc += forceY; velocity += acc * dt; // get velocity velocity *= pow(dampingCoeff, dt); // apply damping variablePosition += velocity * dt; // gravity-affected weight // Vector from reference point to end point after being affected by gravity variableVector = variablePosition - pivotPosition; // a Position - b Position : b->a vector }
内容的提问来源于stack exchange,提问作者Keastmin
相关产品推荐
相关产品推荐

