07-13-2024, 11:56 PM
The mass computation in my physics engine is based upon the following code by Randy Gaul.
https://github.com/RandyGaul/ImpulseEngi...er/Shape.h
https://github.com/RandyGaul/ImpulseEngi...er/Shape.h
Code: (Select All)
void ComputeMass( real density )
{
// Calculate centroid and moment of interia
Vec2 c( 0.0f, 0.0f ); // centroid
real area = 0.0f;
real I = 0.0f;
const real k_inv3 = 1.0f / 3.0f;
for(uint32 i1 = 0; i1 < m_vertexCount; ++i1)
{
// Triangle vertices, third vertex implied as (0, 0)
Vec2 p1( m_vertices[i1] );
uint32 i2 = i1 + 1 < m_vertexCount ? i1 + 1 : 0;
Vec2 p2( m_vertices[i2] );
real D = Cross( p1, p2 );
real triangleArea = 0.5f * D;
area += triangleArea;
// Use area to weight the centroid average, not just vertex position
c += triangleArea * k_inv3 * (p1 + p2);
real intx2 = p1.x * p1.x + p2.x * p1.x + p2.x * p2.x;
real inty2 = p1.y * p1.y + p2.y * p1.y + p2.y * p2.y;
I += (0.25f * k_inv3 * D) * (intx2 + inty2);
}
c *= 1.0f / area;
// Translate vertices to centroid (make the centroid (0, 0)
// for the polygon in model space)
// Not really necessary, but I like doing this anyway
for(uint32 i = 0; i < m_vertexCount; ++i)
m_vertices[i] -= c;
body->m = density * area;
body->im = (body->m) ? 1.0f / body->m : 0.0f;
body->I = I * density;
body->iI = body->I ? 1.0f / body->I : 0.0f;
}
2D physics engine https://github.com/mechatronic3000/fzxNGN
Untitled Rouge-like https://github.com/mechatronic3000/Untitled-Rougelike
QB Pool https://github.com/mechatronic3000/QBPool
Untitled Rouge-like https://github.com/mechatronic3000/Untitled-Rougelike
QB Pool https://github.com/mechatronic3000/QBPool