Skip to content

Instantly share code, notes, and snippets.

@gunstein
Last active September 18, 2021 06:19
Show Gist options
  • Save gunstein/9e3f47067a87a0ef9d497927a13cd0c6 to your computer and use it in GitHub Desktop.
Save gunstein/9e3f47067a87a0ef9d497927a13cd0c6 to your computer and use it in GitHub Desktop.
BevyRapier_howto_change_center_of_rotation_question
use bevy::prelude::*;
use bevy_rapier2d::prelude::*;
use bevy_rapier2d::rapier::na::Vector2;
use nalgebra::{Isometry2};
fn main() {
App::build()
.insert_resource(WindowDescriptor {
title: "Player Movement Example".to_string(),
width: 1000.0,
height: 1000.0,
..Default::default()
})
.add_plugins(DefaultPlugins)
.add_startup_system(spawn_player.system())
.add_system(player_movement.system())
.add_plugin(RapierPhysicsPlugin::<NoUserData>::default())
.run();
}
struct Player;
fn spawn_player(
mut commands: Commands,
mut materials: ResMut<Assets<ColorMaterial>>,
mut rapier_config: ResMut<RapierConfiguration>,
) {
// Set gravity to 0.0 and spawn camera.
rapier_config.gravity = Vector2::zeros();
commands
.spawn()
.insert_bundle(OrthographicCameraBundle::new_2d());
let sprite_size_x = 100.0;
let sprite_size_y = 40.0;
// While we want our sprite to look ~40 px square, we want to keep the physics units smaller
// to prevent float rounding problems. To do this, we set the scale factor in RapierConfiguration
// and divide our sprite_size by the scale.
rapier_config.scale = 20.0;
let collider_size_x = sprite_size_x / rapier_config.scale;
let collider_size_y = sprite_size_y / rapier_config.scale;
// Spawn entity with `Player` struct as a component for access in movement query.
commands
.spawn()
.insert_bundle(SpriteBundle {
material: materials.add(Color::rgb(0.0, 0.0, 0.0).into()),
sprite: Sprite::new(Vec2::new(sprite_size_x, sprite_size_y)),
..Default::default()
})
.insert_bundle(RigidBodyBundle {
body_type: RigidBodyType::KinematicPositionBased,
..Default::default()
})
.insert_bundle(ColliderBundle {
position: [collider_size_x / 2.0, collider_size_y / 2.0].into(),
..Default::default()
})
.insert(ColliderPositionSync::Discrete)
.insert(ColliderDebugRender::with_id(0))
.insert(Player);
}
fn player_movement(
keyboard_input: Res<Input<KeyCode>>,
rapier_parameters: Res<RapierConfiguration>,
mut player_info: Query<(&Player, &mut RigidBodyPosition)>,
) {
for (player, mut rbodypos) in player_info.iter_mut() {
let mut next_rotation_angle = rbodypos.position.rotation.angle();
if keyboard_input.pressed(KeyCode::Space)
{
next_rotation_angle += 0.06;
}
else
{
next_rotation_angle -= 0.06;
}
let clamped_angle = next_rotation_angle.clamp(-0.3, 0.3);
rbodypos.next_position.rotation = Isometry2::rotation(clamped_angle).rotation;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment