Skip to content

Instantly share code, notes, and snippets.

@RJ
Created September 2, 2024 12:29
Show Gist options
  • Save RJ/ad0d778a80609e581b7b2c1496512f9b to your computer and use it in GitHub Desktop.
Save RJ/ad0d778a80609e581b7b2c1496512f9b to your computer and use it in GitHub Desktop.
Modified fixed_joint_2d example with rotation axes note
use avian2d::{math::*, prelude::*};
use bevy::{ecs::component::StorageType, prelude::*};
use examples_common_2d::ExampleCommonPlugin;
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
ExampleCommonPlugin,
PhysicsPlugins::default(),
))
.insert_resource(ClearColor(Color::srgb(0.05, 0.05, 0.1)))
.insert_resource(SubstepCount(50))
.insert_resource(Gravity(Vector::NEG_Y * 1000.0))
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2dBundle::default());
let square_sprite = Sprite {
color: Color::srgb(0.2, 0.7, 0.9),
custom_size: Some(Vec2::splat(50.0)),
..default()
};
let square_sprite2 = Sprite {
color: Color::srgb(1.0, 0.7, 0.9),
custom_size: Some(Vec2::splat(50.0)),
..default()
};
let anchor = commands
.spawn((
SpriteBundle {
sprite: square_sprite2.clone(),
..default()
},
RigidBody::Dynamic,
AngularVelocity(1.5),
))
.id();
let object = commands
.spawn((
SpriteBundle {
sprite: square_sprite,
transform: Transform::from_xyz(100.0, 0.0, 0.0),
..default()
},
LockedAxes::ROTATION_LOCKED,
RigidBody::Dynamic,
MassPropertiesBundle::new_computed(&Collider::rectangle(50.0, 50.0), 1.0),
))
.id();
let joint_entity = commands
.spawn(FixedJoint::new(anchor, object).with_local_anchor_1(Vector::X * 100.0))
.id();
commands.entity(object).insert(Docked {
target: anchor,
joint: joint_entity,
});
}
#[derive(Debug, Reflect)]
pub struct Docked {
pub target: Entity,
pub joint: Entity,
}
// when Docked is added, we need to remove axis locks, so ship can rotate along with asteroid.
impl Component for Docked {
const STORAGE_TYPE: StorageType = StorageType::Table;
fn register_component_hooks(hooks: &mut bevy::ecs::component::ComponentHooks) {
hooks.on_add(|mut world, entity, _component_id| {
if let Some(locked_axes) = world.get_mut::<LockedAxes>(entity) {
info!("Unlocking rotation for entity: {entity}");
locked_axes.unlock_rotation();
}
});
hooks.on_remove(|mut world, entity, _component_id| {
if let Some(locked_axes) = world.get_mut::<LockedAxes>(entity) {
info!("Locking rotation for entity: {entity}");
locked_axes.lock_rotation();
}
});
}
}
@RJ
Copy link
Author

RJ commented Sep 2, 2024

output:

Screen.Recording.2024-09-02.at.13.33.28.mov

@RJ
Copy link
Author

RJ commented Sep 2, 2024

ugh nevermind, just realised unlock_rotation() returns self! so it wasn't assigned to the component 😢

@RJ
Copy link
Author

RJ commented Sep 3, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment