bevy_rapier icon indicating copy to clipboard operation
bevy_rapier copied to clipboard

`Collider::convex_mesh()` produces surprising results

Open leftmostcat opened this issue 5 months ago • 3 comments

When using Collider::convex_mesh(), I seem to consistently get a center of mass "outside" the shape, causing the resulting body to behave incorrectly. The following is a simple repro case with a regular tetrahedron, which I expect to fall, collide with the "table", and come to rest quickly. Instead, it will fall and then begin spinning for an extended duration.

I suspect that I'm specifying the indices incorrectly, but there is no documented ordering or other restrictions, either on Collider::convex_mesh() or the underlying implementations.

use bevy::prelude::*;
use bevy_rapier3d::prelude::*;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_plugins(RapierPhysicsPlugin::<NoUserData>::default())
        .add_plugins(RapierDebugRenderPlugin::default())
        .add_systems(Startup, set_up_camera)
        .add_systems(Startup, set_up_physics)
        .add_systems(Update, bevy::window::close_on_esc)
        .run();
}

fn set_up_camera(mut commands: Commands) {
    commands.spawn(Camera3dBundle {
        projection: Projection::Perspective(Default::default()),
        transform: Transform::from_xyz(0.0, 10.0, 0.0).looking_at(Vec3::ZERO, Vec3::Z),
        ..default()
    });
}

fn set_up_physics(mut commands: Commands) {
    commands
        .spawn(Collider::cuboid(100.0, 0.1, 100.0))
        .insert(TransformBundle::from(Transform::from_xyz(0.0, 0.0, 0.0)));

    commands
        .spawn(RigidBody::Dynamic)
        .insert(Velocity::default())
        .insert(
            Collider::convex_mesh(
                vec![
                    Vec3::new(-0.5, 0.0, 0.0),
                    Vec3::new(0.5, 0.0, 0.0),
                    Vec3::new(0.0, 0.0, 0.866025404),
                    Vec3::new(0.0, 0.816496581, 0.433012702),
                ],
                &[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]],
            )
            .unwrap(),
        )
        .insert(TransformBundle::from(Transform::from_xyz(0.0, 9.0, 0.0)));
}

leftmostcat avatar Mar 20 '24 00:03 leftmostcat