Fix the physics integrator
The velocity component never got updated. Instead, the system was only calculating the current frame's deltaV. That instantaneous dV and any velocity that *did* get assigned (bundle insertion, keyboard control) would be added to the position. Now forces are integrated into velocity, and velocity is integrated into position. You know... like a real integration function.
This commit is contained in:
@@ -1,16 +1,23 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
#[derive(Component, Deref, DerefMut)]
|
||||
#[derive(Component, Default, Deref, DerefMut)]
|
||||
pub struct Velocity(pub Vec3);
|
||||
|
||||
#[derive(Component, Default, Deref, DerefMut, PartialEq, Debug)]
|
||||
pub struct Force(pub Vec3);
|
||||
|
||||
pub fn apply_velocity(mut query: Query<(&mut Transform, &Velocity, &mut Force)>, time: Res<Time>) {
|
||||
for (mut transform, velocity, mut acceleration) in &mut query {
|
||||
let delta_v = **acceleration * time.delta_secs();
|
||||
**acceleration = Vec3::ZERO;
|
||||
let delta_position = (**velocity + delta_v) * time.delta_secs();
|
||||
transform.translation += delta_position;
|
||||
pub fn apply_velocity(
|
||||
mut query: Query<(&mut Transform, &mut Velocity, &mut Force)>,
|
||||
time: Res<Time>,
|
||||
) {
|
||||
for (mut transform, mut velocity, mut force) in &mut query {
|
||||
// integrate forces into new velocity (assume mass of 1kg)
|
||||
let delta_v = **force * time.delta_secs();
|
||||
velocity.0 += delta_v;
|
||||
force.0 = Vec3::ZERO; // clear force value
|
||||
|
||||
// integrate velocity into position
|
||||
let delta_p = **velocity * time.delta_secs();
|
||||
transform.translation += delta_p;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user