#Avian Physics

1 messages · Page 43 of 1

vestal minnow
#

of course the downside is that some internal state may not be entirely up to date for a bit since the updates are deferred, but this would mostly be for internal stuff that isn't very user-facing anyway

#

and batch processing should be better for perf than a dozen observers firing for each added/removed body

hoary turret
#

I could try recreating a minimal example for you to track it down

#

but from what you're saying it looks like you might want to delay it further until you refactor it

#

tell me if you'd fancy the reproducible example and I'll see what I can do

#

however, one more thing @vestal minnow, what time would you say is the best to insert the disabled component? I'm trying to use an observer and some avian-inserted component to delay the insertion of Disabled until Avian has setup all of its internal things

#

the thing is that inserting an entity with Disabled directly is borked af, however if I manually trigger the insertion with (for example) a key input then there's no problem

#

so I'm trying to find the sweetspot for automatic insertion 😅

hallow mulch
#

Hello and thank you for avian, it's pure magic.

#

I'm testing avian on a simple game (with rollback), detecting collisions with observers works fine.

#

One thing i'm not sure how to do, is determine which parts (sides) of the colliders come into contact. In this case it's just a ball with a circular collider and some obstacle with a rectangular collider.

visual sparrow
hallow mulch
#

Is it correct that "Collisions" used to be a bevy Resource, and now it's a SystemParam ?

#

Because i saw a project of someone using bevy_ggrs and avian, and he had some code to register "Collisions" as a resource to be rolled back.

#

Is it enough to just rollback CollidingEntities ?

visual sparrow
#

@cinder summit ^

hallow mulch
#

total_normal_impulse() ?

cinder summit
#

What I roll back now is ContactGraph and ConstraintGraph, I also disable IslandPlugin and IslandSleepingPlugin on avian to avoid mispredictions caused by those not being deterministic if the simulation wasn't spawned in the exact same order

hallow mulch
#

Nice. I don't get any desyncs.

#

I don't rollback Position, only my VirtualPosition.

#

Ok, i think i found it, ContactPoint.

#

Is it wrong to use Collisions from an observer ?

visual sparrow
acoustic brook
#

How is the progress of the kinematic controller group ? Just to know since the posted links have expired

acoustic brook
#

thanks

visual sparrow
#

@vestal minnow thanks a bunch of implementing Default on Collider

#

I got worried for a second there that a certain pattern wasn't possible

vestal minnow
#

...I did?

visual sparrow
#

but behold! It implements it with a unit cube, lovely

#

oh wait it's parry

#

lol

vestal minnow
#

oh lol

visual sparrow
#

alright, convert my praise into: please implement Default for Collider in peck

#

hehe

#

wait no

#

this is avian

#

there we go, real Joona code

vestal minnow
#

why is that 0.5x0.5 thonk

visual sparrow
#

convert my plead back into praise

visual sparrow
#

heh

#

wonder how many users it would break to change

vestal minnow
#

probably a leftover from when it was half lengths

visual sparrow
#

good times

vestal minnow
#

It literally does nothing, it's just a placeholder basically

visual sparrow
#

I need it as a placeholder that I late-init in an on_add hook

#

so for me Empty would certainly be good enough

hallow mulch
visual sparrow
#

e.g. directly into the Z axis

cosmic root
hallow mulch
#

@cinder summit When i use bevy_ggrs in synctest mode (just local players) with avian, it reports desyncs as soon as there's a collision, doesn't happen in the normal p2p mode ... strange

past cargo
#

is avian stateless ?

cinder summit
#

Nope, though you can disable certain behaviors to have it behave much less stateful, like disabling warm starting, and disabling simulation islands and the associated island sleeping plugin

#

I think @vestal minnow had some ideas on how some of these features could get a stateless version eventually though 🤔

vestal minnow
#

Jolt's parallel union-find algorithm to build islands from scratch each tick, plus some non-incremental greedy graph coloring for the constraint graph

#

the lack of warm starting would be quite bad for stability, but Unity DOTS physics has some cursed heuristics that it uses to improve stability without contact caching, which is something we could try

hoary turret
#

@vestal minnow can I get ur attention for a bit about the PR I put up yesterday?

#

I've noticed some more weird behavior after the fix (and I've explained it in the PR already)

#

and I've been thinking that the "correct" solution for this would be to just have an observer on colliders On<Add, Disabled> that removes the collision

#

instead of changing the current function like I did in my PR

#

what do you think?

#

in theory you're already accounting for it here, but something isn't working :/

hallow mulch
#

In which bevy schedule do avian collision event observers run in ? When you use .observe() with CollisionEventsEnabled.

visual sparrow
#

PSA: hot-swapping a Collider at runtime works fine! It recalculates the ColliderAabb as expected 🙂

cinder summit
visual sparrow
cinder summit
visual sparrow
#

but didn't actually know for sure

cinder summit
#

What ... I mean I've seen all the code for it and knew it works bavy

hallow mulch
#

I'm seeing this weird behaviour: when running the game on desktop (1v1), i never get any desyncs on collisions. On wasm, i get desyncs every time there's a collision with the ball.

#

And the ball collision handling is done with an .observe(), that's why i'm wondering if the problem isn't because i'm mutating the ball velocity outside of the ggrs schedule. All my systems run before PhysicsSet::Prepare.

cinder summit
hallow mulch
cinder summit
hallow mulch
#

So if you do: .add_plugins(PhysicsPlugins::new(RollbackUpdate)) .. then your observers will run in RollbackUpdate ?

cinder summit
#

Yep. though if it's in the update one you'll have to order many things to run before physics, which is why it's usually in the PostUpdate versions

hallow mulch
#

I use .before(PhysicsSet::Prepare)

#

Thank you very much for the infos @cinder summit

visual sparrow
#

@vestal minnow is there any difference between controlling a kinematic body by settings its transform vs by setting its velocity?

#

i.e., does Avian do anything "fancy" if I am a good citizen and use the velocity instead of teleporting a kinematic body?

#

(not counting interpolation)

vestal minnow
#

There may also be differences in how well e.g. speculative collisions work

visual sparrow
#

alright, then I'll set the velocity where possible 🙂 thanks!

vestal minnow
#

Velocity is also important since it applies the movement over several substeps

#

However with collide and slide you may need to do something different, since you essentially have a known target position that you want to move to (the output of the algo), and the collide and slide algorithm itself is not integrated with substepping

visual sparrow
#

that's also what the KCC prototype does

#

when I instead set the velocity, I get a lot of penetration

#

which means I'm setting the velocity wrong ofc

#

but there is a certain neatness in just saying "okay, for this velocity you calculated, please just advance as far as you can before penetrating"

vestal minnow
#

I believe Rapier does just set the transform, not sure what engines typically do here

hard helm
# past cargo is avian stateless ?

All simulations have state. If this is for rollback, what you need is the ability to copy all state that can’t be reconstructed. My physics has warm start and other state, but it can all be copied.

vestal minnow
#

"stateless" as in "cacheless", Unity's ECS physics also markets itself as "stateless"

hard helm
#

That doesn’t make a lot of sense. How is the last position not considered state, but previous contact forces considered state?

#

“Cache” implies it can be recalculated, but is stored to improve performance, but these can’t be recalculated.

visual sparrow
cinder summit
#

I mean the previous contact forces are kind of a problem when networking, if those are necessary you kind of can't just connect to a simulation midway anymore, since those depend on the one in the frame before, which depended on the frame before that, etc etc

vestal minnow
hard helm
cinder summit
#

You could do that, but that would cost a decent chunk of bandwidth, so if you're networking over the internet you really don't want to do that

hard helm
cinder summit
#

Yea, the tradeoffs exist, but usually you can implement better options than just "disable this feature entirely because it's impractical for networking"

#

Currently avian doesn't really give you options though, you either get the features, or don't get the features bavy

hard helm
past cargo
#

idk how nise did client prediction with avian not being state less

#

seens pain

#

btw you made avian 3x faster, is this faster than rapier now? @vestal minnow

vestal minnow
#

In general no, but it's getting there

#

Very close for most scenes

cinder summit
cinder summit
vestal minnow
#

and they're also working on other things like their GPU physics

past cargo
#

what you think you could improve to make it as fast as rapier jondolf?

vestal minnow
# past cargo fr?

see their wgmath (wgsl) or nexus (slang) repos for rigid body physics, or slosh for MPM simulation

#

very WIP though

#

wgmath (wgrapier, wgparry, etc.) is probably the more developed one, but still missing a lot feature-wise

past cargo
#

your one is cpu right?

vestal minnow
#

yes, like almost every game physics engine

past cargo
#

from nvidia

#

PhysX

#

but PhysX have no determinism

vestal minnow
#

nah, PhysX is mostly on the CPU

past cargo
#

what

#

it says its on gpu

vestal minnow
#

at one point they were going heavy on GPU physics but then they backtracked

past cargo
#

"Yes, NVIDIA PhysX can run on a GPU to accelerate physics calculations for games and other applications. It is designed to use the processing power of NVIDIA GeForce GPUs (8-series and later) for effects like destruction, fluids, and other dynamic simulations."

vestal minnow
# past cargo it says its on gpu

My understanding is that PhysX started out as a way to do physics on PPUs (old dedicated "physics processing units"), and later transitioned to GPU physics using CUDA. From what I've heard, they've kinda phased out GPU simulation for rigid bodies (though I think it does support it as an option), but does run fluid sim and soft body sim and other stuff like that on the GPU

#

Not 100% sure on what the state of their rigid body GPU sim is though

#

Also, GPU physics via PhysX is limited to Nvidia GPUs

vestal minnow
#

plus we could adopt some optimisations that rapier also added recently, like a cheaper friction model for 3D that just applies a single tangential Coulomb friction constraint and a twist constraint for each contact manifold, rather than applying Coulomb friction to each contact point separately

#

I believe Bepu also uses this simplified friction model

hard helm
#

It’s hard to optimize a physics library without a concrete application. There’s too many different directions for optimization, all with trade offs.

#

In my experience, flexibility is often more important than performance, as long as minimum thresholds are met - it’s more binary; there’s some things you can do, and some you can’t. It doesn’t matter much if you make the things you can do faster, unless that makes something else possible, like walls modeled as individual bricks instead of slabs. The rule of thumb is that these sorts of changes require 10x improvements.

#

Although these can build up over time. I guess my point is that a small (2x) difference in performance shouldn’t be a big deal unless there are no other differences.

past cargo
cinder summit
#

Is it? Being "as fast as rapier" seems like a pointless requirement. Avian has some major limitations atm, but once we fix those it should be good enough for a majority of all game uses

visual sparrow
cinder summit
#

Well yes, but I don't think Jondolf's intent was "it needs to be faster than rapier 2 years from now"

#

Like we already outperform rapier from when avian released now, I think. But Jondolf said that was a goal later than that, and there are some major flaws rapier didn't have but avian did

#

Like how making many many static colliders destroys performance even though they won't collide with eachother

cinder summit
#

(Easy enough to fix with a BVH)

#

I say like slapping a BVH into avian is easy when my PR is still open

#

-# Send help

visual sparrow
#

I remember when collider transform propagation used to go through all hierarchies even if there were no colliders, and people with deep hierarchies like skinned meshes got single digits FPS

#

good old days

visual sparrow
cinder summit
#

I should probably get my PR into a state where someone that actually knows parry can throw the last bit in and we can merge it 🤔

blazing sluice
#

many many static colliders
how many is many many?

cinder summit
#

Most people that reported issues had over 10k

#

It's mostly because it scales exponentially

#

It exponentially scales a few trivial checks just to early out against all other static colliders

blazing sluice
#

hmm, in the broadphase?

cinder summit
#

Yep!

#

Having a BVH and only searching collisions for entities that could collide, would massively speed this case up, while providing a slightly smaller speedup for many dynamic-dynamic entities

blazing sluice
#

Aaah that will improve matters significantly! I'm always surprised how well sweep and prune performs, seems like it shouldn't be quick.

cinder summit
#

The scaling of a BVH is much more efficient than what we do either way, but it might be slower on really small purely dynamic body worlds

cinder summit
#

I mean I'd make a fluid sim seperately

#

Also fluid sims don't have small numbers of entities usually!

blazing sluice
#

my game turns into a fluid sim when there's too much debris tbh, I don't think it's an uncommon case

fossil pendant
#

ok I'm not sure if this is a known issue, but I have a disabled entity with a disabled collider as a child. When cloning that entity the positioning gets all messed up

#
commands
  .spawn((Disabled, Transform::from_xyz(0.0, 10.0, 0.0))
  .with_child((Disabled, Transform::default(), Collider::sphere(0.5)))
#

if I clone this, it results in the child being position at global 0,0,0

fossil pendant
#

when I don't insert the collider and then clone it, the child ends up at global 0, 10, 0

vestal minnow
#

ignoring raw performance numbers, especially our broad phase is kind of abysmal and simply does not scale well for large scenes even if they're completely static, which I would not want for "official" physics

#

but yeah, once we fix those few remaining bottlenecks and ideally add SIMD, we should be pretty good on the performance front

vestal minnow
#

I'd like to stay focused on Peck until I've made the repo public, mainly I just need to fix up my 2D EPA, clean up some APIs and docs, and add convex polygons and polyhedra (and probably compound shapes)

#

I would then consider it "usable", though stuff like trimeshes are missing atm

#

finishing the BVH stuff would probably be my next priority though, besides helping Jan with KCC work where needed

past cargo
#

it was on the list they sent here

vestal minnow
#

who is "they"

past cargo
# vestal minnow who is "they"

i dont remember, hey jondolf do you play make avian stateless on future? cause on the way its rn it sucks for rollback right?

vestal minnow
#

I will aim to support using less state, but not "stateless" by default since that inherently tends to be much slower and less stable

past cargo
#

i see

cinder summit
#

Fast and stable by default but optionally cross platform deterministic and stateless seems like the right approach tbh

vestal minnow
#

But yes I want to support networking scenarios better, whatever the details of that end up being

past cargo
#

cross platform deterministic is a thing already i guess

hallow mulch
#

Is there a way to retrieve the size of a collider after the component has been inserted ? Say you add a Collider::rectangle(), can you then get the physical size of the collider from a query ?

fossil pendant
little maple
fossil pendant
#

yeah I have

#

the issue is I still need the bevy disable Component

#

which is what I guess is causing some issues

#

specifically, if I spawn an entity with a RigidBody and Disabled, then clone it and insert a transform, that transform's translation gets overwritten to be at 0, 0, 0

fossil pendant
#

(rotation and scale stay at the values I inserted)

vague pebble
#

I think I caught a weird interaction dont know if it should be considered a bug

#

If you add a RigidBody to an element that already had a rigid body it is transform gets a little cuckoo

hallow mulch
#

An entity with multiples bodies ? 🤔

vague pebble
#

because me has no brain juice

#

thread 'main' (71702) panicked at /home/sirmadeira/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/avian3d-0.4.1/src/dynamics/solver/islands/mod.rs:650:9: assertion failed: island.contact_count > 0
Has anyone else came across with this assertion error?

dry jolt
#

does anyone know of an example on how know when things collide. im using avian3d and want to have some sound effects when things collide.

visual sparrow
hallow mulch
oblique swift
#

Hi,

Shouldn't Position and any user-facing components like Rotation, LinearVelocity, etc. only get overwritten if the new value is actually different from the previous one?

For example here: https://github.com/avianphysics/avian/blob/bf498f387977e318ff7be176c33472f1b5963c7a/src/dynamics/solver/solver_body/plugin.rs#L275

Do something like this instead:

let old_world_com = *rot * com.0;
let new_rot = (solver_body.delta_rotation * *rot).fast_renormalize();
if *rot != new_rot {
    *rot = new_rot;
}

let new_world_com = *rot * com.0;
let new_pos = pos.0 + solver_body.delta_position + old_world_com - new_world_com;
if pos.0 != new_pos {
    pos.0 = new_pos;
}

// Write back velocities only if changed
if lin_vel.0 != solver_body.linear_velocity {
    lin_vel.0 = solver_body.linear_velocity;
}
if ang_vel.0 != solver_body.angular_velocity {
    ang_vel.0 = solver_body.angular_velocity;
}

This would keep the Bevy change detection accurate.

past cargo
#

not stateless

spiral nymph
vague pebble
#

I am saying the tranform of the entity acts weirdly, specially if it is a child

fossil pendant
royal helm
#

Is the debug stuff retained or immediate gizmos?

#

ah seems immediate

hallow mulch
#

When you despawn an entity which has a Collider, is it immediately effective or can there still be collision events on the next frame even though the entity is about to be destroyed ?

dreamy viper
vestal minnow
#

I've been focusing mostly on Peck and Jan's KCC work, so apologies if I'm a bit slow at responding to things 😅

vestal minnow
#

I think you can get CollisionEnd events though if it was touching other colliders when it was despawned

hallow cove
#

hiiii all! im having an issue where i have two static cuboid colliders right next to each other (to panels in a level im building), where when i roll my dynamic sphere across the seam between the two, there often a little hitch/jump, which seems to be caused by the sphere encountering the edge of the second cuboid, even though it's at exactly the same height as the first cuboid. This seems to be called a phantom collision, and i was wondering if there were any easy ways to prevent this

#

is there a utility method for collecting a bunch of colliders and combining them into a single voxel grid shape?

#

do trimeshes solve the problem as well?

sweet sundial
#

iirc trimeshes have a specific countermeasure
there's also a voxels collider iirc? may have weird characteristics

dreamy viper
bleak wadi
#

@vestal minnow it's been a while, i haven't really been working on my game much but i've come back to it, and i've still got that problem where disabled hitboxes fall when they're not supposed to, and also trigger the no mass or inertia warning

sweet sundial
#

are you disabling the rigidbody or the collider

bleak wadi
sweet sundial
#

a rigidbody with no enabled colliders has no mass and no impediment to gravity

#

try telling it to sleep maybe

bleak wadi
#

btw is it a good approach for a sword to enable and disable the collider and sprite when not being swung? for a terraria style swing

bleak wadi
sweet sundial
#

insert the Sleeping marker component

sweet sundial
bleak wadi
#

i still have the same issue

#

this worked before 0.17 btw

sweet sundial
#

i remember seeing several Disabled-related bugfixes, possible that's related
what was the previous and/or intended behavior

bleak wadi
sweet sundial
#

turn off gravity or make it kinematic then

#

though overriding its Position with its Transform+Parent does sound like a reasonable handling of the situation

past escarp
#

any clue why im getting really unstable behavior at first with these revolute joints?

relevant spawner code:

 let wheel_entity = {
  cmd.spawn((
      RigidBody::Dynamic,
      Collider::cylinder(wheel_radius, wheel_thickness),
      Mass(10.0),
      Friction::new(0.9).with_combine_rule(CoefficientCombine::Max),
      CollisionLayers {
          memberships: InteractionLayer::Car.into(),
          filters: InteractionLayer::Default.into(),
      },
      Transform::from_rotation(Quat::from_rotation_z(
          std::f32::consts::FRAC_PI_2,
      )),
  ))
  .id()
};

cmd.spawn((RevoluteJoint::new(target, wheel_entity)
  .with_local_basis1(Quat::from_rotation_y(std::f32::consts::FRAC_PI_2))
  .with_local_basis2(Quat::from_rotation_x(std::f32::consts::FRAC_PI_2))
  .with_local_anchor1(Vec3::new(
      (half_width + wheel_thickness) * x_sign,
      0.0,
      half_depth * z_sign,
  ))
  .with_local_anchor2(Vec3::ZERO)
  .with_hinge_axis(Vec3::Z),));
#

it seems kinda random, sometimes it spawns in without issue

flat root
#

Hi folks! I'm facing an issue and I'm unsure if it comes from the library or some issue with how bevy deals with custom Disabled components.

Let me break down the issue:

  • I'm registering a custom Disabled component that I add/remove on a State change for entities matching a certain QueryFilter.
  • These entities have a Collider (at least most of them).
  • I'm spawning other entities that also have a Collider, and CollidingEntities component.
  • I run a system that will process any collisions with these entities by iterating its CollidingEntities and doing stuff (like, for example, damaging the other entities).
  • Everything works normally until I add and remove this custom Disabled component. After that, CollidingEntities in my damaging entities always contains 0 entities.

Is this a known issue or is this a typical problem with these custom disabled components that the bevy docs warns about? Thanks a lot in advance!

viral goblet
#

I think its an avian bug?
A playtester was playing and I wasn't looking so I have no idea what caused this

past escarp
coral kite
#

Is the joint solve order in Avian fully deterministic?

hallow mulch
#

thread 'main' panicked at /usr/local/rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:1995:13:
swap_remove index (is 0) should be < len (is 0)
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace
Encountered a panic in system avian2d::collision::narrow_phase::update_narrow_phase<avian2d::collision::collider::parry::Collider, ()>!
Encountered a panic in system avian2d::schedule::run_physics_schedule!
Encountered a panic in system bevy_roll_safe::schedule::run_schedules!
Encountered a panic in system <bevy_ggrs::GgrsPlugin<bevy_ggrs::GgrsConfig<u8, matchbox_protocol::PeerId>> as bevy_app::plugin::Plugin>::build::{{closure}}!

#

I've seen this panic a few times now, just wanted to share it.

#

Also getting some panics with "Contact pair not found in graph: ContactId(0)".

cinder summit
#

Considering ggrs is involved here ... Do the ContactGraph and ConstraintGraph get rolled back?

hallow mulch
#

I was trying to understand the role of ConstraintGraph

#

ContactGraph can't be rolled back as far as i'm aware

cinder summit
#

Iirc those two are linked in a way. If things are contacting this creates constraints to solve, and other things like joints also create constraints, thus if you roll back one you need to roll back both

#

Not rolling back either also sort of works but I think that can cause determinism issues

hallow mulch
#

Ok, interesting.

visual sparrow
#

@vestal minnow I'm done triaging Avian salute

#

There's a whole bunch of issues like "hierarchies of colliders do something unexpected" and there's not really a label for that

#

specifically for the ECS-ness of stuff

#

Like how things behave in Children hierarchies, how it interacts with Disabled, things about required components...

#

Maybe an extra label would be good

#

Then there's a whole bunch of issues that are "I have ghost collisions"

#

not sure what to do with those?

echo parcel
#

Is it really just for cubes? What should I use if my world is procedural, but more "smooth"

cinder summit
#

That said, I didn't have great luck with that personally in the past, which is part of why my SDF collisions exist now

vestal minnow
vestal minnow
vestal minnow
# visual sparrow not sure what to do with those?

Hmm, not sure... There's not too much we can do about ghost collisions, beyond providing shapes that don't suffer from them (which we already have for meshes and voxels), and maybe adding something like Jolt's "enhanced internal edge removal" (#612)

#

We might just want to create some centralized issue that we link to from all the scattered issues, and close those ones

#

And also have a good section on ghost collisions in docs

visual sparrow
vestal minnow
# coral kite Is the joint solve order in Avian fully deterministic?

Not yet because it uses Query iteration order, which isn't guaranteed in Bevy. It will most likely be reworked though to not use queries for the core solver, since we need that for graph coloring and SIMD optimizations anyway. So it should hopefully get fixed in the future

#

The joint solve order should only cause problems for joint chains

#

Ex: if you have two bodies connected by a joint, and those bodies don't have any other joints, it should be fully deterministic even if joints exist elsewhere in the world

#

Other than that, I'm not really aware of determinism problems in Avian, other than how networking can complicate things

vestal minnow
coral kite
echo parcel
#

How should I approach making the movement system(something simple, like just flying including collision). I've added trimesh collisions to my chunks, and a sphere collider to my character. How should I now move the character in a avian way?

sweet sundial
#

accelerate it
up to you whether to pay attention to mass or existing velocity

visual sparrow
echo parcel
# visual sparrow If you want a dynamic rigid body, just add a force

I've added LinearVelocity component, and set velocity with:

for (mut player_transform, _player, mut linear_velocity) in player_query.iter_mut() {
            //player_transform.translation = player_transform.translation + temp_translation;
            linear_velocity.0 = normalized_direction * 200.;
        }

But the character didn't move

#
        Collider::sphere(5.),
        RigidBody::Dynamic,
        LinearVelocity::default(),

These are the avian components I have on a given character

echo parcel
visual sparrow
echo parcel
#

Is having other components, like Transform::from_translation(Vec3::new(32., 32., 32.)), could impact how avian works?

sweet sundial
#

does it wake the body

#

entitycommands.remove::<Sleeping>(), yk

#

happens automatically with the forces querydata

echo parcel
# sweet sundial entitycommands.remove::<Sleeping>(), yk

Still nothing

for (entity, mut player_transform, _player, mut linear_velocity) in player_query.iter_mut() {
            //player_transform.translation = player_transform.translation + temp_translation;
            commands.entity(entity).remove::<Sleeping>();

            linear_velocity.0 = normalized_direction * 200.;
        }
sweet sundial
#

and normalized_direction isn't zero?

echo parcel
visual sparrow
#

can you try applying a force instead? with Forces

echo parcel
# visual sparrow can you try applying a force instead? with `Forces`

Still nothing:

mut player_query: Query<(Entity, &mut Transform, &MovementComponent, Forces)>,
for (entity, mut player_transform, _player, mut forces) in player_query.iter_mut() {
        //player_transform.translation = player_transform.translation + temp_translation;
        commands.entity(entity).remove::<Sleeping>();

        let mut velocity = forces.linear_velocity_mut();
        *velocity = normal_dir * 200.;
        //linear_velocity.0 = normal_dir * 200.;
    }
sweet sundial
#

...lol

echo parcel
#

Still nothing

#

Hmm... I think I know why

#

Does Forces need to be explicitly added into entity?

#

If I add Forces to query it no querries 0 items

sweet sundial
#

should be automatic for any rigidbody

echo parcel
#

Then I think for some reason its not being added

#

This is how I spawn the player:

let player_entity = commands.spawn((
        Player {
            velocity : Vec3::ZERO,
            gravity : 9.8,
            speed : 20.0,
        },
        Transform::from_translation(Vec3::new(32., 32., 32.)),
        Visibility::default(),
        MovementMonitor::new(Vec3::new(32., 32., 32.)),
        MovementComponent {  },
        Collider::sphere(5.),
        RigidBody::Dynamic,
        LinearVelocity::default(),
        LocalEntity,
    )).id();
sweet sundial
#

shouldn't need LinearVelocity either

echo parcel
#

Should it be ForcesItem instead of just Forces?

sweet sundial
#

what if you remove whatever Player::{velocity, gravity} is for

sweet sundial
#

is the repo public somewhere

echo parcel
echo parcel
echo parcel
#

Ok, I found the issue

#

Finally

#

Ofc. it was something very stupid

#

Missing PhysicsPlugins::default()

#

Ok, collisions work

#

But, how can I disable them? I've noticed that with lot of chunks the colliders add up to lag condireably

paper trellis
sweet sundial
echo parcel
# sweet sundial ColliderDisabled, or make sure they're all static

Or? They are all static, but I wonder if just the sheer amount of vertices is not just impacting the performance, bcs. after adding ColliderDisabled component it doesn't change anything in terms of performance.

Should I add collider on the fly when player enters new chunk, or am I doing something wrong?

echo parcel
visual sparrow
cinder summit
valid zenith
#

@vestal minnow was working on portals yesterday and noticed that if i try to teleport in an observer it just never teleports, but if i stick it in a System it works perfectly

Now that I know that the camera jitter issue is related to updating transforms between physics steps, i can intuit that this is probably the same thing, but it does raise the question.

If i DO need to make arbitrary modifications to the transform of a physics object, what is the correct system timing to do this in?

on the docs it says to do it in PostUpdate but before the transform propogations, but in my case just running the system in Update fixed everything so im not sure if the PostUpdate rule is more so like "A known safe timing" or if its actually genuinely needed and i just got lucky.

cinder summit
#

I think that might be an old reccommendation. Avian used to run inPostUpdate by default, but that's FixedPostUpdate now, which runs before Update

#

What event is your observer responding to?

visual sparrow
#

for portals, probably not, right?

#

If you teleport in FixedUpdate, it will work, but it will also interpolate, which is not what you want here

#

I'm not sure which schedule is best for what you want hmm

#

Maybe you could use FixedUpdate and yeet the interpolation components manually on those ticks?

cinder summit
visual sparrow
#

I think that one is not re-exported by Avian, so you'll have to add a dependency on bevy_transform_interpolation

#

Which, to be clear, you already have anyways transitively

#

maybe just setting start to None in your teleportation tick could work

valid zenith
cinder summit
#

I assume your observer was something like a collision event?

visual sparrow
valid zenith
visual sparrow
cinder summit
#

I'd imagine all you need to fix those is buffer the change till after physics, or maybe change Position and Rotation directly instead of Transform

#

But ofc if you have interpolation that can be its own problem to solve

valid zenith
#

thats probably how it actually got fixed, because i didnt move the collision into a system, i had it emit a teleport event that i read in an update.
So it wouldve had a built in 1 frame lag between the collision and the teleport LUL

cinder summit
#

The event would probably get picked up by the Update later in that frame, but it could cause issues if your FPS dropped en you ran a couple of FixedUpdate loops in one frame

#

Ideally the change would get processed in FixedPostUpdate after physics ran, or try that Position/Rotation thing so the physics immediately respond to it 🤔

valid zenith
#

FixedPostUpdate sounds fine actually.
if it runs after the physics systems id be able to read the collision event in a system instead of an observer and do the transform with 0 frame delay right?

cinder summit
#

Yep

valid zenith
#

aight yeah ill just do that then.

does feel a bit weird moving gameplay systems that touch transforms directly into a PostUpdate schedule, since yk, postupdate atleast by the definition should be for stuff that responds to updates, like cleanup or engine stuff ykyk.
But it is what it is NODDERS

echo parcel
visual sparrow
echo parcel
cinder summit
#

If you update them often you also get problems like how trimesh colliders are slow (but immediate), while convex decomp is fast but needs some time to process, you can use this to your advantage by swapping new chunks out with trimeshes, then processing them in the background and putting the more efficient collider when done

#

Similarly when loading new chunks

#

Also, everything performs better with less veritices, so running a simplification pass on your meshes might be worth it too

visual sparrow
echo parcel
cinder summit
#

I think there were a couple of third-party plugins for it at least

visual sparrow
#

@vestal minnow do RigidBodys not get Position and Rotation if their colliders are children? hmm

#

oh wait Colliders are also not getting those either in my test

#

I guess I set the test up wrong hmm

#

Ooooh I see, I forgot

.insert_resource(TimeUpdateStrategy::ManualDuration(
    Time::<Fixed>::default().timestep(),
))
lucid forge
#

Hello, I do not found an equivalent of CollidingEntities that also match when a collider if fully inside the second, does one exist or does this ability need to be implemented by hand with the collision triggers (On<CollisionStart> & On<CollisionEnd>) ?

visual sparrow
#

trimeshes are always "hollow", hence why you don't get a collision when one thing is fully inside another

#

but try e.g. a convex decomposition and CollidingEntities should report that 🙂

lucid forge
#

Oh I didn't check the type of meshes, I will try that, thank you 🙂

echo parcel
#

Gravity is a reasource, not a component O.o?

visual sparrow
vestal minnow
#

for per-entity gravity, you can use ConstantLinearAcceleration, just make sure to disable global gravity or use GravityScale::ZERO

echo parcel
#

But only if character didn't touch anything. After the touch the lag is gargantuous

little maple
#

does move-and-slide have a lot more overhead than the conveyor belt setup if I'm doing kinda the same thing?

visual sparrow
vestal minnow
#

Move-and-slide is intended for kinematic bodies, and not integrated with the actual simulation loop, I'm not sure how you'd use it for this

#

Perf-wise, it does some shape casts and computes contact manifolds, while with CollisionHooks you're not really doing anything extra beyond your conveyor belt logic

little maple
#

ah, cool. Yeah, I was curious but I think the collision hooks might work better for what I'm doing (using dynamic bodies)

visual sparrow
#

@vestal minnow what are the semantics of changing Transform in PreUpdate?

#

or not semantics, but rather effects on interpolation

#

I think it disables interpolation for that frame and respects the new transform, which is what I want

#

But I find that it weirdly enough doesn't change the position when running on Web hmm

#

Very possible this is a user error by me, but just checking in case you know anything about that

vestal minnow
#

but I don't remember if I've tested exactly that setup

torn hedge
#

i'm currently experiencing this crash and i'd like to debug it but have no idea what might cause it

thread 'Compute Task Pool (8)' panicked at C:\Users\zwaze\.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\avian3d-0.4.1\src\dynamics\solver\plugin.rs:398:51:
index out of bounds: the len is 1 but the index is 1
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Encountered a panic in system `avian3d::dynamics::solver::plugin::prepare_contact_constraints`!
Encountered a panic in system `avian3d::schedule::run_physics_schedule`!
Encountered a panic in system `bevy_app::main_schedule::FixedMain::run_fixed_main`!
Encountered a panic in system `lightyear_prediction::rollback::run_rollback`!
Encountered a panic in system `bevy_app::main_schedule::Main::run_main`!
#

any idea?

#

i use ligthyear and have PhysicsInterpolationPlugin, PhysicsTransformPlugin and the IslandPlugin disabled for it

vague pebble
#

Guess you could just handle it?

torn hedge
#

the panic comes from avian directly

#

i'm just wondering what might cause it, like am i missing a component? its definitely lightyear that causes it as only the client crashes but the host is fine. so i'm trying to figure out what is missing

sweet sundial
#

are the ContactGraph and ConstraintGraph being rolled back differently

dry quartz
#

Hi guys I have a little confusion here

struct Player;

#[derive(Component)]
struct PressurePlate;

fn setup_pressure_plates(mut commands: Commands) {
    commands.spawn((
        PressurePlate,
        Collider::cuboid(1.0, 0.1, 1.0),
        Sensor,
        // Enable collision events for this collider.
        CollisionEventsEnabled,
    ))
    // Observer for responding to collisions starting with the pressure plate.
    .observe(|trigger: Trigger<OnCollisionStart>, player_query: Query<&Player>| {
        // The trigger target is the entity that the observer is targeting.
        let pressure_plate = trigger.target();

        // The `collider` stored in the event is the entity that the target entity collided with.
        // There is also a `body` field for the rigid body that the collider is attached to.
        let other_entity = trigger.collider;

        // Check if the entity colliding with the pressure plate is a player.
        if player_query.contains(other_entity) {
            println!("Player {other_entity} stepped on pressure plate {pressure_plate}");
        }
    });
}```
#

in this code: player_query return a query of Player component, but in the if statment player_query .contains take a entity?

#

so what contains do exactly?

cinder summit
#

contains checks if an entity matches a query, rather than actually fetching the data for the query

lapis isle
#

I'm trying to setup Avian to run server side. Right now my server side code just runs with bevy MinimalPlugins and StatePlugins. Avian crashes as there are resources, etc missing which I imagine get setup when you use the DefaultPlugins in bevy. I was wondering if anyone could point me to a resource, or let me know what the minimum Plugins they needed to use to get Avian working on the server side. Thank you.

cinder summit
#

I think it might depend on the features you have enabled on avian. Avian with milimal plugins works for me iirc

lapis isle
#

I'm initializing avian with PhysicsPlugin::default(). In my code I'm only trying to add a Collider and RigidBody

cinder summit
#

My guess is it would be complaining about things like meshes or asset events not existing because things like processing of colliders from meshes are enabled by default 🤔

lapis isle
#

Encountered an error in system avian3d::collision::collider::cache::clear_unused_colliders: Parameter MessageReader<AssetEvent<Mesh>>::messages failed validation: Message not initialized
If this is an expected state, wrap the parameter in Option<T> and handle None when it happens, or wrap the parameter in If<T> to skip the system when it happens.

#

Yes, you're correct

cinder summit
#

Gonna want to set the features for avian to the minimum amount in your Cargo.toml I guess
Something like this:

avian3d = { version = "0.4", default-features = false, features = ["3d", "f32", "parry-f32", "default-collider", "xpbd_joints"] }
lapis isle
#

Ok, I'll give that a try. Thank you!

hallow mulch
#

I'm playing with the tnua character controller with avian2d, using tiled maps. I'm using a RayCaster to detect entities within a certain distance, which works. I add objects in the map with the tiled editor.

hallow mulch
#

It seems that for each tile, object, .. in the tiled map, there isn't 1 but 2 entities, the tile entity and another one. I'm using bevy_ecs_tiled. The RayCaster query hits an entity but not the one i'm looking for.

#

fn detect_portals(
portals: Query<Entity, With<Portal>>,
mut rays: Query<(&mut RayCaster, &mut RayHits)>,
mut gizmos: Gizmos
) {
for (ray, hits) in &mut rays {
let origin = ray.global_origin().f32();
let direction = ray.global_direction().f32();

    for hit in hits.iter() {
        gizmos.line_2d(origin, origin + direction * hit.distance as f32, GREEN);

        if portals.contains(hit.entity) {
            info!("We're close to a portal: {:?}", hit.entity);
        }   
    } 
}   

}

vestal minnow
#

Either way I'd try to figure out what the "other" unwanted hit entity actually is

#

It could be that tnua is also adding its own sensor collider or something that you're hitting, I don't remember if it uses colliders or just spatial queries

hallow mulch
vestal minnow
#

It will look for any Collider in the scene along the path of the ray

hallow mulch
viral goblet
#

Is there a built-in way to write something like "acknowledge collisions with layers a and b, unless the collider has collision layer c"?

sweet sundial
#

i don't think the current system can collide with some layers l but not l|c

#

it's "any filter of a overlaps with b AND any filter of b overlaps with a"

late cape
#

Hey, so there is this wireframe-blink-on-contact thing and I am not sure if this is normal and how I would disable it...been searching for an hour but somehow to blind to find any mention/config about it... :/

sweet sundial
#

at some point you're removing Sleeping but not resetting the SleepTimer so it keeps sleeping for one tick every time it elapses

#

sleeping bodies have dimmer wireframes

late cape
# sweet sundial

oh nice, I did not think about frame stepping a recording, thx :p

late cape
sweet sundial
#

what's the character controller

late cape
#

ohh

#
fn movement_damping(mut query: Query<(&MovementDampingFactor, &mut LinearVelocity)>) {
    for (damping_factor, mut linear_velocity) in &mut query {
        linear_velocity.x *= damping_factor.0;
        linear_velocity.z *= damping_factor.0;
    }
}

This is basically copypasta from the dynamic_character_3d example, it causes this apparently

sweet sundial
#

o7

peak timber
#

Ghost collisions are so annoying 😭

visual sparrow
quartz saffron
#

Is there a way to get the area of a parry3d shape ? m2 or others or i have to implement it myself on the shapes ?

vestal minnow
#

To get the volume, you'd just compute the mass given a density of 1, because then volume = mass / density = mass / 1.0 = mass

#

For a Collider:

let volume = collider.mass(1.0);
#

For a Parry SharedShape:

let volume = shape.mass_properties(1.0).mass();
hallow mulch
#

Good evening. Another question about tiled maps, avian2d and tnua. I use tnua to control my character. I've just added moving platforms. I can stand on the platform but the character doesn't move with the platform, it stays in the same position while the platform moves. Definitely related to the fact that tnua is a floating character controller isn't it ? Anyone familiar with tnua here ?

#

The platform's RigidBody is Kinematic

#

When the character is in crouch position, the character's collider and the platform's collider intersect.

#

maybe related to Friction ..

#

Ok i've found some documentation on this: "Moving platforms can be implemented by updating the Position or Transform of a kinematic or static body. For platforms that carry dynamic bodies, ensure that collision response is handled so that passengers move with the platform."

#

Just need to implement the second part with a system then.

cloud jasper
#

That's weird - Tnua should be able to handle that. The moving platform in the Avian 2D demo is a kinematic rigid body, and the character moves along with it without having to crouch.

#

Is your code uploaded anywhere public?

sweet sundial
#

check that the platform is moved using velocity

hallow mulch
hallow mulch
#

Will use LinearVelocity to see if it makes a difference.

cloud jasper
#

Doesn't a kinematic rigid body that get moved by altering its position also automatically get its velocity updated? Or is that only in Rapier?

sweet sundial
#

no idea, but if they're using tnua that might be the issue

hallow mulch
#

In the tnua repository, in the 2d platformer demo, there's a MovingPlatformPlugin.

#

Wow!

#

With LinearVelocity, it works !

#

@sweet sundial Much respect, thank you.

sweet sundial
#

np
otherwise you're basically teleporting the platform

vestal minnow
#

You can easily do it manually though by just setting velocity to (target_pos - pos) / dt

unreal scaffold
#

I wish for detecting collisions between specific entities you could do On<CollisionStart, insert entity here> instead of checking if a query contains them

little maple
#

hmm, that would mean triggering that event for every collision start even if you don't care, right?

unreal scaffold
#

Couldn't tell you myself 😔

little maple
past cargo
#

did you already saw newtow dynamics @vestal minnow ?

vestal minnow
#

I know they exist but haven't looked into them too much

past cargo
past cargo
vestal minnow
#

stateless or stateful

#

Avian and Rapier also support cross-platform determinism and are stateful

past cargo
vestal minnow
#

rollback determinism is different from cross-platform determinism

#

Box2D is also cross-platform deterministic but not rollback deterministic

past cargo
#

i see

#

well hope avian let us do roolback on future

vestal minnow
#

You can do rollback with both Avian and Rapier, it's just not trivial to get it working nicely and with Avian you need to disable some things

#

like simulation islands and maybe warm starting

#

and roll back resources like the contact graph and constraint graph

past cargo
#

you know, how about just have a way to force island simulation and warm starting when you want?

#

cause after all its just values

vestal minnow
#

The problem is mainly the persistent state. Islands are persisted across frames, and if the data is not correct or up to date, your program can crash, and it's hard/expensive to roll back all that data properly and keep everything in sync across clients

past cargo
#

i see, wise jondolf

vestal minnow
#

We'd ideally want to rebuild islands from scratch each frame with something like Jolt's parallel union-find algorithm, so you don't need to cache any of that state or send it over the network

past cargo
#

jondolf, iam excited to see your work

vestal minnow
#

which is slower in performance, but plays nicer with networking

past cargo
#

fr

#

like you are doing this alone

#

and its hard as f

past cargo
#

like i wanted to know wich States right now are problem for roolback, just Island and Warm?

vestal minnow
#

warm starting (=initialize the contact solver with the previous frame's impulses) is the second problem yeah, I feel like you should be able to just roll back that data but IIRC it didn't work for some people, so I'm not sure

#

you can disable it if you need to, at the cost of having worse stability for stacking scenarios (like a stack of blocks)

past cargo
#

yeah i see you have some trouble with stacking scenarios xd

#

Newton Dynamics also fixed it, idk how, but it have no problem with shake, well i wont take lot of your time iam being annoying xd, gl bro, hope avian get implemented into bevy officialy soon @vestal minnow

echo parcel
#

Can I find somewhere complete documentation on collisions? I want to know what options I have available

sweet sundial
echo parcel
sweet sundial
#

you mean colliders?

echo parcel
#

Yes

sweet sundial
#

or for something much more advanced you could impl AnyCollider yourself

echo parcel
sweet sundial
#

it won't collide with something inside it

#

like if it was an empty cardboard box

echo parcel
#

Shouldn't matter for me

#

I think trimesh_from_mesh will do then

sweet sundial
#

iirc the bevy-blender toolkit has the ability to define components on objects, so you could use the reflectable collider constructors for primitive shapes like that

#

don't know about the toolkit though

acoustic spoke
#

anyone have a problem where a falling collider (like a character falling post-jump) "intersect" the ground colliders by a pixel for like a few frames or so?

#

it's such a subtle issue physics-wise but it really affects my character control, e.g. all horizontal velocities are reset to 0, and it can't jump again instantly because its y velocity from the jump impulse gets immediately overridden

sweet sundial
#

what controller do you use? that sounds more extreme than would normally happen with just physics

acoustic spoke
#

i'm not too keen on adding even more dependencies but it is what it is

acoustic spoke
#

now in the case where i press the jump button and hold it till the character lands, i'd expect it to jump.
which it "does", because that jump! gets printed

#

except at that frame the character collider is intersecting with the ground collider, so the velocity gets cancelled out

sweet sundial
#

what cancels that velocity, though? ramp countermeasure or something?

acoustic spoke
#

you can see that when she lands, for a moment her collider is 1 pixel inside the ground

sweet sundial
#

could maybe try turning up speculative collisions

#

-# ... i wonder if integer coordinate avian is possible

acoustic spoke
sweet sundial
#

... hey, isn't the down momentum at the end of a jump exactly equal to that at the start with reversed direction?

#

you might be perfectly cancelling your fall

#

can try logging the velocity right before and after adding the impulse

acoustic spoke
acoustic spoke
#

i might be adding the velocity when it was still falling

#

...well changing it from += to = didn't change anything, so i'm not sure

sweet sundial
#

better to check it now before trying to find things elsewhere that might touch velocity at that moment

acoustic spoke
#

okay yeah lmao

acoustic spoke
#

not to keen on the = part though, that might mess things up if i wanna add some things like moving elevators

sweet sundial
#

can branch on the sign of the existing velocity, or vel = vel.max(0.0) + dv;

#

i do a lot of "if it's going the wrong direction, fix that; otherwise just add"

acoustic spoke
#

i see, thanks for the suggestion

#

what about elevators moving downward though? she would jump way higher than she should

#

ehhh it's probably fine, that's what most players would probably expect

sweet sundial
#

could make the reference the relative velocity of the object she's grounded on

acoustic spoke
#

ahh like Query<&LinearVelocity>ing the ground entity?

#

arghhhh Forces mutably borrows LinearVelocity so i can't make the query

sweet sundial
#

can just query its Forces then :p

acoustic spoke
#

the Forces query is already par_iter_mut()-ed d:

#

oh no no wait i could just store the velocity on the grounded check instead

sweet sundial
#

par_iter on a player's component sounds a bit unoptimal

acoustic spoke
#

all my enemy entities will share the same controller component

#

with mocked action values

#

so my AI components in the future could just tell the entity where to move and not worry about how they move

sweet sundial
#

fair enough

faint kite
#

Hello! I probably misunderstand something, but how many times does this move the character controller? E.g. if there are 4 points, each 1 meter deep, the character controller will be pushed 4 meters instead of 1 meter, isn't it? Perhaps I just don't understand contact manifolds correctly (couldn't find a proper image of it) or something else.

GitHub

ECS-driven 2D and 3D physics engine for the Bevy game engine. - avianphysics/avian

acoustic spoke
#

does Dominance affect joints? or the better question, is there a way to make joints completely avoid applying forces to the first body? i'm trying to make a nice-looking hair with distance joints and they always end up messing my player's movements

#

oh whoa it actually does!

little maple
acoustic spoke
little maple
acoustic spoke
little maple
acoustic spoke
#

nope, i'm just a high schooler struggling with high-level physics 👍

#

rn i'm just asking chatgpt for a general algorithm and write my own rust version to my Hair component

acoustic spoke
#

you're way too kind

little maple
#

could be useful if you manage to get something working. I made a game with joints that were used to attach limbs that swung around and it worked pretty well but I do remember struggling a bit with some instability at first and then when I tried doing it on the vehicles it was unstable and also affected the vehicle so I set it aside. Wonder if something changed.. I'll post something here if I get time to try again and make some progress

hallow mulch
#

When you use a RayCaster (with Dir2::X, horizontal) with a circle Collider, is it normal if the ray isn't horizontal but points down a bit ?

#

As the character moves, the circle collider seems to "roll", and the ray starts to point towards the ground.

hallow mulch
#

Doesn't happen with a rectangular collider, definitely linked to the collider's shape, makes sense.

acoustic spoke
blazing sluice
#

@wet niche thanks for the pointer to modify_contacts. What a powerful feature. I've been having a great time implementing destruction physics. Finally crashing has severe consequences!

hallow mulch
dense current
#

How can i apply an impulse on spawn to rigidbody at specific point on rigid body ?

merry gulch
#

Hello. I'm trying to use new MoveAndSlide algorithm to implement a character controller. I've copied the example code and tried to add gravitation. But now it simply slides along the ground even though I've added the Dir::Y plane to config. Below is the code and video demonstration of what happens. What should I change to make it not slide and stand still when it's grounded?

// in `run_move_and_slide` same as the system in the examples
            &MoveAndSlideConfig {
                planes: vec![Dir3::Y],
                ..default()
            },

// system to apply gravity
fn apply_gravity(time: Res<Time<Fixed>>, mut controllers: Query<&mut LinearVelocity>) {
    let delta_time = time.timestep().as_secs_f32();

    for mut linear_velocity in &mut controllers {
        linear_velocity.0 += 9.8 * delta_time;
    }
}

// regestrations
.add_systems(
  FixedUpdate,
  (player_movement, apply_gravity, run_move_and_slide).chain(),
)
vestal minnow
#

That system is applying a gravity of Vec3::new(9.8 * delta_time, 9.8 * delta_time, 9.8 * delta_time) to the linear velocity

#

you want to just apply it to the y component

#

I'm also not sure why you're applying a positive (=upwards) gravity unless your y-coordinates are flipped 🤔

past escarp
#

Do colliders no longer scale according to their transform in 0.4?

sweet sundial
#

my asymmetrically scaled sphere's still working

vestal minnow
#

Yeah it should work

vestal minnow
#

By the way, for those not on the Avian Character Controller Working Group server, there was a kind of mini-revolution and it was rebranded to a more general Avian Dev server 😄
https://discord.gg/xJaYNZvd

#

The general Avian community and user questions will remain here on the Bevy server and in this #1124043933886976171 thread, and upstream physics discussions will still be held in #physics-dev

#

So not much has really changed, this is just a kind of smaller sub-community for discussing the development of Avian and related crates (like Peck, or Jan's bevy_ahoy KCC) and collaborating there, or for discussing any other interesting physicsy things

#

A bonus is that you get the Avian feather as an emoji by being on the server 😛

hallow mulch
#

Is this code wrong ?

#

#[derive(EntityEvent)]
pub struct TeleportEvent {
pub entity: Entity,
pub destination: Vec3,
}

fn on_teleport(
event: On<TeleportEvent>,
mut transforms: Query<&mut Transform>,
) {
if let Ok(mut transform) = transforms.get_mut(event.entity) {
transform.translation = event.destination.clone();
}
}

#

I trigger teleport events when an entity collides with a portal, "destination" being the coordinates of the place the portal sends to. The event is triggered, the transform is changed, and the entity isn't moved.

sweet sundial
#

when in the schedule are you sending these events

hallow mulch
#

The entity isn't moved, and keeps bumping on the portal's collider.

#

I'm not changing this entity's transform anywhere else in the code

sweet sundial
#

try updating Position instead

hallow mulch
#

Hmm is Position part of avian ?

sweet sundial
#

yes

hallow mulch
#

Ah so avian uses Position internally

sweet sundial
#

depending on when the observers are triggered, the position+rotation/transform sync systems might ignore one or the other

hallow mulch
#

That's exactly what seems to be happening

#

Will try it now, thanks !

hallow mulch
#

So mutating a Transform with avian entities is wrong.

sweet sundial
#

works fine with scheduled systems

echo parcel
#

When creating collider:

let mesh3d = Mesh3d(meshes.add(Cuboid::new(1000.0, 10.0, 1000.0)));

    let mesh = match meshes.get(&mesh3d) {
        None => {
            return;
        }
        Some(item) => {
            item
        }
    };

    let collider = Collider::trimesh_from_mesh(&mesh).unwrap();

    commands.entity(entity).insert((
        mesh3d,
        MeshMaterial3d(materials.add(Color::srgb(0.5, 0.5, 0.5))),
        TestTag,
        Block {
            display_name: "Test platform".to_string(),
            id: 0
        },
        collider
    ));

Should I store it somewhere in order to not have to recreate it over and over?

sweet sundial
#

i assume the first line isn't part of the code
you can use a HashMap<AssetId, Collider>
that's worthwhile because Collider is an Arc<dyn Shape>

hallow mulch
#

Is it appropriate to use a momentary circle Collider to represent the explosion of a bomb 💣 ? If the player is in the middle of the explosion and the colliders don't intersect, would that generate a collision ?

sweet sundial
#

if it's not a polyline

#

most colliders are solid

#

if you just want whether something would collide with a circle at a location at a precise moment, use a spacial query

#

or a Sensor on a collider

hallow mulch
fleet field
#

Hello. Does anyone have an example of integrating the one_way_platform example (https://github.com/avianphysics/avian/blob/main/crates/avian2d/examples/one_way_platform_2d.rs) with proper detection if the entity is on the ground? I am trying to write a system to add Grounded component to the player entity using a ShapeCaster, but it gets complicated when the player is colliding with a one way platform. If they are above the platform, they should be Grounded, but if they are just inside of the platform (ie. not all the way through it on their jump), Grounded should not be added

fleet field
#

for anyone also wonder how to do this, I managed to make the ShapeCaster from Collider::segment - so I just made it a horizontal line, with origin at the bottom of the player's collider. Before I was trying to use a ShapeCaster from the player's rectangular Collider, which means it registered hits inside the player, instead of only below the player

echo parcel
sweet sundial
#

assuming you want multiple colliders from the same mesh at least

sweet sundial
#

can probably set something up to read asset drop events and remove relevant colliders from the map, or just use weak arcs in the map
for optimization

hallow mulch
#

If you want to have two or more RayCaster on an entity, it's best to create child entities which hold a RayCaster, and declare a relationship ? or is there a better approach.

sweet sundial
#

that's probably fine, but in some situations (ie, only need the raycast every so often) spacial queries are better

hallow mulch
#

I'm making a cat platformer game, and the mice detect danger ahead with a forward raycaster, but i'm thinking of adding another one in the opposite direction 🙂

#

So yeah i'm constantly querying the raycaster in a system

viral goblet
#

It started happening when I activated the debug plugin (debug collider gizmos and all)

sand smelt
# viral goblet o no

This usually means that stuff has become NaN. Avian doesn't have enough debug asserts to catch these, so the crash usually happens when updating AABBs even though the first NaN appeared somewhere else.

#

I tracked one of them down in my project, and it ended up being a bug in collision manifold generation, causing my character controller to make a LinearVelocity negative infinity, causing positions to be NaN, causing AABBs to be NaN

viral goblet
#

huh

sand smelt
#

It would probably be a good idea for avian to have a debug_assert!(x.is_finite()) every time a component is read or written to the ECS, otherwise it takes so long to figure out where it happens

#

But no clue why it would happen just because of a debug plugin. Do you have a deterministic way to reproduce it?

viral goblet
#

No idea why tbh

sand smelt
viral goblet
#

On another note- I noticed that activating the parent activates the children colliders but not vice-versa. Am I doing something wrong? Is there away to make the children detect the collision?

little maple
#

anyone else running into these errors trying to compile avian?

the trait bound AngularInertiaTensor: From<glam_matrix_extras::SymmetricMat3> is not satisfied

little maple
#

ok, I just checked out main and did a cargo update and it seems to be working 🤷‍♂️

faint kite
#

@vestal minnow
Hello!

  1. I am currently using the main branch and the move_and_slide function. The character controller slides down the slopes, is it gonna be fixed?
  2. How can I change max slope angle?
  3. Is steps climbing gonna be implemented?
  4. Any ETA on the stable version?
  5. Is there gonna be complete character controller component?
vestal minnow
# faint kite <@545959292281552928> Hello! 1) I am currently using the main branch and the `m...
  1. We haven't updated the KCC examples in the repo yet, so they still don't use move_and_slide currently. But the plan is to rework them, and also add several new character controller examples (ex: 2D top down, 3D first person...)
  2. The old KCC examples handle slope collision behavior in the kinematic_controller_collisions system, which you'd replace with move_and_slide, but it doesn't have slope handling built-in. You need to check if the character is grounded (= hitting the ground with a normal whose angle to the up direction is below the max slope angle), and if yes, have some logic to prevent sliding down and possibly also snap the character to the ground if you want to stick to slopes.
  3. Most likely yes
  4. I believe Bevy is making a 0.18 release candidate in about a week, so I'll probably do a 0.5-rc release for Avian around that time too. It'll have the move-and-slide stuff. A proper 0.5 release will come later, when Bevy 0.18 is fully released
  5. Yes, the plan is to have a more or less fully featured KCC, with optional slope handling, ground snapping, stair stepping, all that fun stuff. I don't have any specific ETA for this, but I have an early minimal draft for an API already (link), and will try to get the basics working soon-ish
#

If this is 3D, I can heavily recommend bevy_ahoy by @visual sparrow for a KCC

#

It uses Avian's move_and_slide and other related things, and is being actively developed with a ton of really cool stuff

faint kite
vestal minnow
#

Yeah that's just a floating character that you can move around to test sliding against geometry, so yes it's meant to slide down slopes and whatnot, there's no ground handling there

viral goblet
# viral goblet On another note- I noticed that activating the parent activates the children col...

Ok so after hours of debugging I know exactly what's happening but not what to do to fix it.
The small collider is created as a child of a bigger collider. Then, I detach it from the parent (the only thing I do is remove theChildOf component) and reattach it later on.
As long as it has the ChildOf, it detects collisions. When independent, though, it does not.
Why? What can I do to fix it? (even if it's a hack, this collider is crucial for the enemy's main mechanic)

( @vestal minnow )

peak timber
#

Not sure if this is the right place to ask but I've been working on a simple platformer game with bevy-tnua, avian2d, and bevy_ecs_tiled:
https://github.com/Rigidity/avian-tnua-platformer-wip

And I keep running into issues with the player colliding with the edge of the floor like it's a wall, for a moment. I fixed all the clipping issues, so now it just disrupts the velocity of the player.

#

The red rectangle collider doesn't have this issue, but the auto generated map collider(s) by bevy_ecs_tiled do - and as you can see they're combined correctly to avoid ghost collisions (this only happens on the true corners of the map)

#

Here's a video of it happening

faint kite
#

@visual sparrow
Hello! How do I connect bevy_ahoy?

bevy_ahoy = "0.0.1"```
When I write it like this, `kcc.rs` doesn't compile, throws me a dozen of errors.
visual sparrow
#

I forgot

#

gimme a sec 😄

visual sparrow
#

oh wait

#

you need a patch

#

add this:

[patch.crates-io]
avian3d = { git = "https://github.com/avianphysics/avian" }
#

does that help?

faint kite
# visual sparrow does that help?

Now there are only 2 similar errors:
error[E0599]: no method named `depenetrate_all` found for reference `&avian3d::prelude::MoveAndSlide<'_, '_>` in the current scope

visual sparrow
#

or wait

#

huh

#

why do you get that hmm

#

Oooooh I know why

#

depend on https://github.com/janhohenheim/bevy_ahoy directly

#

i.e.

bevy_ahoy = { git = "https://github.com/janhohenheim/bevy_ahoy" }
#

@crisp hazel I think this should cover your problem too

crisp hazel
#

👀 I'll try it tomorrow

faint kite
#

My Cargo.toml looks like this:

...
[dependencies]
avian3d = "0.4.1"
bevy = { version = "0.17.3", features = ["dynamic_linking"] }
bevy_ahoy = "0.0.1"
bevy_enhanced_input = "0.20.0"
bevy_skein = "0.4.0"

[patch.crates-io]
avian3d = { git = "https://github.com/avianphysics/avian" }
bevy_ahoy = { git = "https://github.com/janhohenheim/bevy_ahoy" }
...```
#

Well, now I have:
error[E0277]: the trait bound `bevy_ahoy::prelude::Movement: InputAction` is not satisfied
Even if I copy that macro directly from bevy_ahoy GitHub page.

visual sparrow
#

cargo update -p bevy_ahoy

#

sorry for the trouble, it's all very WIP haha

hallow mulch
faint kite
faint kite
visual sparrow
#

I'll write those once we have mantling and water implemented

faint kite
visual sparrow
#

I hope the handling feels as lovely to you as it does to us heart_lime

hallow mulch
peak timber
#

I guess I'll have to look under the hood.. was thinking it could be using trimeshes and winding vertices in the wrong order

#

but I also don't see two triangles for each rectangle when using the debug plugin, so idk

hallow mulch
#

Would be interesting to see if there's the same problem with ldtk maps.

peak timber
#

I wonder how nobody would notice this though

hallow mulch
#

Have you tried with a rounded rectangle collider ?

faint kite
# visual sparrow Nice! Would you mind giving us feedback when you've set it up? 🙂

It works really well! Although, I've noticed a couple of things.

  1. Dynamic objects fly violently when the character controller approaches them.
  2. If you run left and jump, and then press right midair, velocity negates completely. It feels wrong.
  3. When the character controller moves up a slope and stops, it slowly moves up (and vice versa). Apparently, CharacterControllerCameraOf.enable_smoothing enables or disables it. What are disadvantages if I turn it off? (I haven't noticed any so far.)
  4. What is the difference between speed and max_speed?
  5. If you hold forward and jump, and then look right or left, you will continue jumping towards the original direction, but if you rotate horizontally more than 90°, you will be jumping sideways. It's a bit hard to describe in words, better just to see it once.
  6. What are “tac” and “crane”?
  7. I think if the character controller crouches midair, it should bend its legs, so the camera doesn't drop down. It think it's like that in Half-Life... 🤔
  8. If the character controller runs into a steep slope, it shortly tries to climb it sometimes. Probably not a huge problem though...
  9. Are there any plans for switching between walk/sprint modes? (Although, I guess, it should be possible to just change max speed with a button.)

I haven't checked out all the CharacterController's fields yet because I'm falling asleep.

dry jolt
#

checking out the example for the chain_3d. it uses the SphericalJoint. which is cool because they joint objects in the chain rotate with the movement, but its very springy. I tried the DistanceJoint and that you can fix the joint distance but the joints dont seam to rotate with the movement. is there a way to get the Spherical to not be springy and stretchy in distance?

visual sparrow
# faint kite It works really well! Although, I've noticed a couple of things. 1) Dynamic obj...

thank you very much for typing this up!

  1. that's just the density of the objects being low 🙂 You can set their density higher and will see that they don't fly anymore
  2. That's a feature! It's called counter-strafing
  3. The disadvantages are that things like stair stepping and crouching will teleport the camera, which can be disorienting. I'll tweak the smoothing at some point to this behavior you noticed is better behaved broovy
  4. Yeah I need to improve the naming on the configuration fields haha. speed is how much speed you reach when you hold W on the ground, max_speed is the maximum you can get through movement techniques like airstrafing before the game clamps you
  5. That's also a feature, it's how air control works in Quake-derived KCCs 😄
  6. They're terms from parkour. In this KCC, "tac" means
    - Run and jump so that you jump slightly into a wall. The angle should be about 10 -30 degrees inte the wall (where 0 would be parallel to the wall)
    - press space again when you're touching the wall
    - if you do it right, you will kick off from the wall and gain vertical and horizontal speed. It's our imo more fun version of a wallrun 😉
    "crane" is a move that pulls you up a low ledge without having to full-on grab the ledge and slowly climb it. You jump to an obstacle that is just a bit too high, then press space again when touching it to get up the rest of the way
  7. agreed!
  8. Is that the residual momentum, or an actual climb? If it's the residual momentum, that's expected. i.e. your speed won't go to zero instantly but be "unloaded" on the steep slope
  9. I was thinking it's trivial enough to change the speed yourself (not the max_speed), so it's not builtin rn. But we could add it. I personally much prefer games that where you are instead always sprinting and can optionally slow down with shift, so I also want to try to nudge the users slightly in that direction (it's an opinionated KCC).
#

cc @summer acorn

summer acorn
#

i do agree with 3, im going to have smoothing disabled for my projects

#

im glad its a setting

visual sparrow
summer acorn
#

yup

viral goblet
#

Is there a way to define the PhysicsSchedule to make systems ambigious in order by default?
If I don't specify their order explicitly the app won't run so I have to make meaningless system sets

visual sparrow
#

why do you want it to be ambiguous anyways?

#

inter-system parallelism is usually not something that gives you performance

viral goblet
viral goblet
#

hold on let me show you what happens if I put two systems on the same system-sub-set

#

@visual sparrow it compiles successfully, but then

visual sparrow
faint kite
# visual sparrow thank you very much for typing this up! 1) that's just the density of the object...
  1. Is there any setting for the character controller like “force” with which it pushes objects or how it applies to objects? 🤔 And does only density of other objects control the CC's speed reduction?
  2. Can there be an option to disable it and just gradually change the directional instead? I've just checked in HL2, it's “kinda” like this too, but it feels smoother there. But maybe it's just small acceleration/deceleration? It definitely doesn't get cut off though, like you hit an invisible wall.
  3. Can crouching be made gradual and not instant? E.g. gradually scale the collider's height (maybe even with easing). I recall I made this in Unity ages ago, worked just fine. But, speaking of smoothing, I really hate wobbly cameras in games.
  4. It feels really weird, could you make an option to have an expected behavior? I.e. each new jump follows the intended movement direction (with preserving some velocity, but not 100% of it). If I look north and start jumping towards it, and then I look west while holding W and Space, I'd expect to start jumping west (eventually), not to continue jumping north forever. And if I start jumping north and then suddenly turn 180° south, I definitely shouldn't be jumping towards east or west (with some of the momentum permanently cut off). It just feels like I have no control of the character.
faint kite
# visual sparrow thank you very much for typing this up! 1) that's just the density of the object...
  1. @summer acorn I just checked both Half-Life 1 and 2, and the camera in the first one indeed tucks down, but in Half-Life 2 it doesn't, no feedback there whatsoever, the camera doesn't change vertical position at all. So we can tell with confidence that the devs actually fixed it. And it feels just right, no feedback is really needed. In real life, center of mass is somehere around the chest for males, lower for females, but torso is the core, and arms and legs are just “free attachments”, so to speak (i.e their mass is negligible). Human body isn't a uniform cylinder. If you jump and wave your arms, your eyesight height doesn't change. Same if you bend your legs midair. I actually encourage you to try it out. I tried, nothing changes. And even if you want to tuck your head (no idea why you would), it's 3 cm tops. Anyway, to please everyone, there could be a setting for how much one wants to tuck the camera during a midair crouch.
  2. Yeah, I think it's residual.
  3. I know what you mean, but it depends on a game too, or rather it's type. In some slow-paced exploration games you'd want slow speed by default with a possibility to run sometimes. And some games may have more than 2 modes, e.g. walk, jog and run. But again, I think it can be done just by changing speed and acceleration/deceleration (for smooth transitions between modes).
visual sparrow
# faint kite 1) Is there any setting for the character controller like “force” with which it ...
  1. it's physics based: increasing the mass (or indirectly the density) of the KCC will make it more forceful. The speed reduction is a byproduct of trying to not intersect with the other objects, so the more they get thrown, the less your speed is decreased.
  2. It's based on the flavor used in CS:Source. I can look into the code difference to HL2 at some point, sure 🙂 It's also possible there is some bug or another causing it. Will need to investigate!
  3. The smoothing is only vertical FYI. No mouse smoothing, no smoothing when you walk. It's only up and down. The crouch can certainly be made gradual, yes, though the code would be a liiiittle bit tricky to write due to Parry's API. The smoothing on stairs would also not be needed at all if we could use capsules, but there's a Parry limitation regarding reported normals that keeps us from using them :/
  4. Probably not, no. Changing the air acceleration has big repercussions on the feeling and supported movement tech, and implementing two entirely different air accelerations is a lot of testing overhead, as all features must feel nice with both. You actually have a surprising amount of air control, you just need to know how via air strafing. That said, I know that the airstrafing is not yet quite perfect, so this may improve a bit in the future.
visual sparrow
#

Update: can confirm that 3) and 5) are both accurate to the Counter Strike controller

#

I forgot to mention, but the air control depends on you pressing A/D while jumping. The momentum is also never permanently cut off: you can airstrafe up to max_speed while jumping

faint kite
visual sparrow
#

a prominent one is how in HL2, jumping forward speeds you up, while in CS:S, you keep your speed

visual sparrow
summer acorn
#

I actually encourage you to try it out
i do parkour irl, the thing ive been saying to jan is to keep the CoM in the same place when you tuck or untuck from a crouch. the center of the collider is just the approximation that was easiest, but i agree that a more accurate adjustable value would be better

faint kite
# visual sparrow I forgot to mention, but the air control depends on you pressing A/D while jumpi...

I am not sure we are talking about the same thing. I am talking about holding W and Space and nothing else, and moving the mouse around without releasing those 2 buttons. If you rotate 180° without releasing them, you won't jump the opposite direction ever, you will be just jumping in place, so it's “permanently” cut off (until you release Space and start over).
You also didn't reply to my [other message](#1124043933886976171 message).

visual sparrow
visual sparrow
#

I'll defer to vero

visual sparrow
#

just so we talk about the same thing

faint kite
# summer acorn > I actually encourage you to try it out i do parkour irl, the thing ive been sa...

Perhaps, I misunderstood, centre of mass wasn't my concern at all (the body's rotation is locked anyway, so I don't see how it affects anything). Firstly, I was talking about the camera going down if you crouch mid-air, which is not realistic for real life, and as for games, we have HL2 as an example. There are probably more games too, but I consider HL2 as a standard for many things. Secondly, if you mean to cut both top and bottom of the collider, it's not correct, neither for real life, nor for a game (HL2 once again is an example). When you jump, your torso is the core, you may bend your limbs whatever you like, the torso doesn't change altitude because of that, even if you regroup mid-air (even if you swing your limbs violently, you can affect your position only this much). You may lean a bit, but that's already a rotation. So the correct approach is to cut only the bottom part of the collider, so to speak. The main idea of crouching mid-air (besides regrouping and preserving momentum) both irl and in Half-Life games is to reach higher places that you can't reach without crouching. Anyway, as I said, there could be a settings for that.
https://youtu.be/tn0lqMuGguw?si=8jFAxQ9p0v88QY5i&t=8

The standing vertical jump is an important measure of an athlete's explosive power and a critical test in the NFL Combine. So who jumps the highest? And what's the limit? WIRED's Robbie Gonzalez jumps in to examine the physics and physicality of maximum leaping ability.

Still haven’t subscribed to WIRED on YouTube? ►► http://wrd.cm/15fP7B...

▶ Play video
bold garnet
#

When you jump, your center of mass follows a more or less fixed trajectory. Im pretty sure moving your legs up does change your center of mass relative to your torso (your center of mass moves up slightly). This has the effect of moving your torso downward slightly, relative to its previous trajectory. Right?

#

This is just basic conservation, a body in free fall cant pull a mass towards itself without also being pulled towards the mass.

summer acorn
#

yeah the difference is humans cannot move their legs instantly like a videogame character

#

i think tucking towards the center makes more sense than tucking towards the top

#

and i dont think the point of crouching while jumping is to get to higher places

#

the point is to fit in tighter spots

#

although it also lets you get higher places

#

because your feet are less in the way

bold garnet
#

an average person's legs account for about ~30% of their body mass (and about half that is in the upper legs and won't move much), so it's not like it will have a huge effect but it will be noticeable.

summer acorn
#

if you were on a space station and you tucked your legs, your eyes would move down

#

not a whole lot, but not unnoticable

#

the upper legs do move quite a bit when crouching btw

#

the arms do too

visual sparrow
# visual sparrow I assume you mean this?

assuming that this is the behavior you describe, here's how this is done in Quake-derived KCCs. The first jump I do, I only press space + W. You can see I move perpendicular to the original direction, which is quirky, I agree, but not really something fixable with this acceleration style.
The second jump, I press space + W and then hold A or D while moving the mouse. As you can see, you can have very nice air control that way 🙂

visual sparrow
summer acorn
#

yeah

#

i do think having the CoM in a more accurate position is a good idea

#

the eyes are not it though

bold garnet
#

back of the envelop, i'd expect eyes to move down by maybe about 10-15% of the leg height.

visual sparrow
#

the mass ratio between legs and head?

faint kite
# visual sparrow I assume you mean this?

Yes, did you only hold W and didn't press A/D? If so, it's just counter-intuitive. Is it like this in Quake 3?! Either way, it doesn't make any sense. Why am I going north and after rotating to south I am moving east instead (not even initial north direction that would have some logic at least)? If I want to go left, I will press A, don't I? More to that, if you rotate mouse enough times, you will either move towards random direction (not even the initial one) or lose momentum completely and will be jumping in place. Even more to that, if I release W and press A or D, it will do nothing, so yes, I have no control over the CC in this situation, it just jumps in a random direction like a lunatic. Idk, maybe it's a normal thing for certain games, but it is definitely something niche. And if I think it's not normal, I am pretty sure there will be players who will think the same. Sorry, but, unlike the rest of the CC, this part is really unpleasant. 😔

visual sparrow
#

You can go the Team Fortress way and increase the friction by a lot and apply it before the jump

#

that means that every jump is processed completely independently / has no momentum

faint kite
faint kite
visual sparrow
summer acorn
#

specifically those numbers

faint kite
visual sparrow
#

As they note, this fixes certain things, but makes the KCC feel rather bland in the process

faint kite
faint kite
visual sparrow
bold garnet
visual sparrow
faint kite
visual sparrow
faint kite
faint kite
faint kite
#

Are you comparing jumping on Earth and tucking in space?

faint kite
faint kite
faint kite
visual sparrow
#

I'll need to see how I implement the jump crouch at all haha

#

all I know is that the current one is shit

faint kite
visual sparrow
#

the docs are lying btw lol

#

kinematic bodies still get a mass

faint kite
# visual sparrow assuming that this is the behavior you describe, here's how this is done in Quak...

What do you mean by “acceleration style”?
The first jump: from the player's point of view, it is something that should be achievable (and actually must be performed) by pressing A, not W.
The second jump: the problem is pressing A/D doesn't work in my case as it does in your video. It barely affects the direction. Maybe it's my settings though... I didn't change many yet, but I did change speed (it's much lower).

visual sparrow
#

e.g. if you want to turn right, you move the mouse right and hold W+D

visual sparrow
visual sparrow
faint kite
visual sparrow
#

but first I need to finish the climbing implementation

faint kite
faint kite
faint kite
faint kite
visual sparrow
faint kite
# visual sparrow e.g. if you want to turn right, you move the mouse right and hold W+D

Interesting. Initially I thought you were pressing A while turning right and vice versa (kinda like when you jump around some pivot or object), because it looks like that. Perhaps, I am just going crazy... Well, this way it kinda works, but is still weird, although that might be because of low speed in my case. What I still don't get is why, if I start jumping forward, and then press A/D while jumping, regardless of whether W is pressed or not, I don't start jumping 45° or 90° eventually, but just jump forward forever. Because if I press W and A/D, I will walk in a 45° direction, same if I jump just once, but not if I hold Space. Perhaps, it's a feature for Quake and some slice of games, but not something one would expect by default. 🤔

#

And again, it only works if you slowly move the mouse around and in the “right” direction (like in the video).

#

Otherwise you just jump in a random direction or lose speed completely.

#

Maybe it has something to do with times when people used keyboard to rotate instead of mouse... 🤔

faint kite
sweet sundial
#

imo it makes more sense to put the look and input directions together and just react to the resulting movement intent vector

visual sparrow
visual sparrow
sweet sundial
#

i've got "hold space to climb any wall you're touching"

faint kite
visual sparrow
sweet sundial
#

just hold a direction then

visual sparrow
#

if there's a ledge I'm looking at and I'm holding space, I feel like I should be able to climb it

#

but obviously this is personal preference

sleek thicket
#

intuition depends on the games you're used to

peak timber
#

@hallow mulch this fixed the issue for me, something about TiledPhysicsAvianBackend::Polyline (the default) is broken but Triangulation works

#

Though it might have its own issues, not sure lol

#

Got my hopes up...

hallow mulch
#

Nice !

peak timber
#

Avian seems to miscalculate collisions on corners

hallow mulch
peak timber
#

looked through the source code and saw the enum, then found where I could define it

sweet sundial
#

ghost collisions happen when it seems like it might hit an edge if the other edge wasn't there

peak timber
hallow mulch
#

Trying Triangulation now ...

sweet sundial
#

there's a 'voxels' shape, iirc even in 2d

#

and meshes (incl. 2d trimesh) have anti-internal-collision measures

hallow mulch
#

Oh that's weird it splits colliders into sets of triangles

peak timber
#

I guess that's the problem - bevy_ecs_tiled is generating separate colliders rather than an actual trimesh

vestal minnow
#

I would heavily recommend using a voxel collider for tilemaps, though I'm guessing bevy_ecs_tiled doesn't have built-in support for it yet

#

it won't have ghost collisions, unlike Parry's polyline or using a compound of rectangles

peak timber
#

I think the problem is Tiled allows you to use various kinds of polygons as colliders for tiles, and so it has to support arbitrary shapes and combine them on a best effort basis to prevent ghost collisions in between tiles (it does the combining pretty well, but the colliders it generates still have issues on corners)

vestal minnow
#

yeah you'll get those with 2D meshes or polylines since Parry doesn't fix internal edges for those, and even if it did, you'd get ghost collisions at boundaries where different colliders meet even if the surface looks flat

peak timber
#

I tried having Cursor fix the issue in bevy_ecs_tiled and it switched it to convex_decomposition - everything seems to work now, but this could also just be slop that will break in 5 minutes for all I know lol

vestal minnow
#

with a voxel collider you won't get ghost collisions since it's specialized to handle them properly

#

you could also set the SpeculativeMargin of the character to zero to reduce the risk of ghost collisions, you might just overlap things a bit easier when moving at high speeds since you won't have CCD

peak timber
vestal minnow
#

yeah for that you'd need a different shape, which introduces the problem again :/

#

it would be nice if Parry had Box2D's chain shape (described in that article), which would fix the problem that polylines currently have

#

maybe I'll add it to Peck

echo parcel
#

Why is raycaster a component?

use avian3d::prelude::*;
use bevy::prelude::*;

fn setup(mut commands: Commands) {
    // Spawn a ray caster at the center with the rays travelling right
    commands.spawn(RayCaster::new(Vec3::ZERO, Dir3::X));
    // ...spawn colliders and other things
}

fn print_hits(query: Query<(&RayCaster, &RayHits)>) {
    for (ray, hits) in &query {
        // For the faster iterator that isn't sorted, use `.iter()`
        for hit in hits.iter_sorted() {
            println!(
                "Hit entity {} at {} with normal {}",
                hit.entity,
                ray.origin + *ray.direction * hit.distance,
                hit.normal,
            );
        }
    }
}

Do I have to update location and direction of the ReyCaster component every time I want to perform a reycast, or is there some function I missed that should be used for a reycast instead?

vestal minnow
visual sparrow
proper yew
#

is there a way of creating a collider with it's origin offset? like say i want a cylinder but not centered

visual sparrow
proper yew
#

is that significantly worse than a simple shape for calculations? i mean i doubt it can be that bad tho

vestal minnow
#

the general recommendation is putting the collider on a child entity with its own transform, but a Compound works too if you want to keep it on a single entity

#

a compound collider stores a BVH acceleration structure, since they're mostly intended for, well, compound shapes

#

which is completely redundant if you just store one or a few shapes

#

but it still shouldn't be too bad in terms of overhead

proper yew
#

negligible difference though i assume

#

compound shape just works and feels a bit nicer to use than child entities

dense current
#

I have 2 rigid dynamic bodies and i want one of them to not affected by physics, i can't use kinematic because i'm using tnua controller which requires a dynamic body, other entity i'm talking about will be a scene prop like a ball or cube

vestal minnow
#

There's a Dominance component for treating dynamic bodies like they had infinite mass when interacting with lower dominance bodies

acoustic spoke
vestal minnow
#

hmm yeah it probably applies damping to both bodies currently 🤔

acoustic spoke
#

i was trynna make my character hair use rope segments based on revolute joints, and you could imagine the horrors in my face when my sprite started rotating even though it had both Dominance(i8::MAX) and LockedAxes::ROTATION_LOCKED

#

doesn't happen without JointDamping, but that makes the hair unbelievably light which looks silly

dense current
dense current
#

this one is too complex :D

acoustic spoke
dense current
#

I have a weird bug

#
let mut entity = commands.spawn((
        Name::new("Game Scene"),
        Transform::from_xyz(0.0, 0.0, 0.0).with_scale(vec3(5.0,5.0,5.0)),
        RigidBody::Static,
        SceneRoot(scene),
        ColliderConstructorHierarchy::new(ColliderConstructor::ConvexHullFromMesh),
    ));
#

when i use this some of the meshes rotates

#

in the scene

#

more specifically the mountain starts to rotate

echo parcel
#

How can I get hit point location?

sweet sundial
#

distance * direction + origin

#

need direction and origin from wherever you cast the ray

echo parcel
#

I must have some sort of mistake. For some reason, entites are being spawn behind the collider:

    for hit in hits.iter_sorted() {
        let translation = hit.distance * camera_transform.forward() + camera_transform.translation();

Where:

camera_query: Query<(&GlobalTransform, &mut Camera3d, &RayCaster, &RayHits), With<LocalEntity>>,

let (camera_transform, camera, ray_caster, hits) = camera_query.single()?;

Or maybe I have something wrong with the collider creation? Is there a way to visualize the collider?

pub fn test_platform(
    In(entity): In<Entity>,
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>
) {
    let mesh3d = Mesh3d(meshes.add(Cuboid::new(1000.0, 10.0, 1000.0)));

    let mesh = match meshes.get(&mesh3d) {
        None => {
            return;
        }
        Some(item) => {
            item
        }
    };

    let collider = Collider::trimesh_from_mesh(&mesh).unwrap();

    commands.entity(entity).insert((
        mesh3d,
        MeshMaterial3d(materials.add(Color::srgb(0.5, 0.5, 0.5))),
        TestTag,
        Block {
            display_name: "Test platform".to_string(),
            id: 0
        },
        collider
    ));
}   
sweet sundial
#

there's a physics debug plugin

echo parcel
#

Collider seems to be ok

echo parcel
#

So, I made sure that it actually hits the collider plane collider, etc.

#

Is this possible that RayHitData.distance is bugged?

#

When I e.g. ray cast stright down, it actually gives me bigger distance, than when I do it under angle

#

The results are like Y > X

sweet sundial
#

can try visualizing the raycast, either via raycaster's debug viz or just an independent gizmo

echo parcel
sweet sundial
#

use an entity with a transform and raycaster component

echo parcel
#

Finally works

viral goblet
#

This keeps happening to me. I took a look at the avian code but couldn't figure out which constructor could possibly be used for the shape casters that also uses new_unchecked

dense current
#
avian3d::dynamics::rigid_body::mass_properties: Dynamic rigid body 2652v4 has no mass or inertia. This can cause NaN values. Consider adding a `MassPropertiesBundle` or a `Collider` with mass.
#

how can i fix this

sweet sundial
#

make sure it has at least one enabled collider or add a manual Mass

dry jolt
#

im not sure why i need a massproperties bundle and a collider that have the same shape...

#

like if i have

  RigidBody::Dynamic,
  Collider::capsule(0.6, 1.3),
  ColliderDensity(1.5), //default is 1.0

it seams to work but gives that warning when i do

  RigidBody::Dynamic,
  MassPropertiesBundle::from_shape(&Capsule3d::new(0.6,1.3), 1.0),
  Collider::capsule(0.6, 1.3),
  ColliderDensity(1.5), 

it works fine. no warnings.

sweet sundial
#

that sounds more like MassPropertyPlugin isn't added or the scheduling's weird

dry jolt
#

MassPropertyPlugin ? havnt used that...

sweet sundial
#

it's the one that manages mass properties, it's in PhysicsPlugins, but it's also the one that emits that warning

dry jolt
#
.add_plugins(PhysicsPlugins::default())
sweet sundial
#

which is why i went back and crossed it out

dry jolt
#

using the example of the chain_3d with the sphericalJoint. i cant seam to get ti to be non-stertchy. its always springy and stretchy... i got the distanceJoint to work for keeping a distance but the rotation on that joint is not as cool as the sphereicalJoint.

is there a way to get the spehericalJoint to be non springysquishy?

late cape
#

Heyy, I've been very confused with LinearVelocity today. Is there some documentation somewhere on how this is implemented?
Why does the initial Transform.translation of a RigidBody influence the direction in which the LinearVelocity is applied?
The following is the example that made me cry about whatever is happening:

if let Some((pos, _)) = named.iter().find(|(_, name)| name.as_str() == "hand_ik.R") {
    let direction = -camera.translation.with_y(0.).normalize();
    let transform = Transform::from_translation(pos.translation());
    dbg!(transform, direction * 10.);
    commands
        .spawn((
            Mesh3d(meshes.add(Sphere::new(0.1))),
            MeshMaterial3d(materials.add(ArcaneMaterial::new())),
            transform,
            Collider::sphere(0.1),
            RigidBody::Dynamic,
            GravityScale(0.),
            LinearVelocity(direction * 10.),
        ));
}
late cape
#

Here the sphere moves to the right normally, but when the starting Transform changes (the hand of the character moves) it then moves forward.
The dbg output for one sphere that goes to the right and one that moves forward is:

[game/src/player/attack.rs:40:9] transform = Transform {
    translation: Vec3(
        3.1421115,
        1.5768347,
        8.041592,
    ),
    rotation: Quat(
        0.0,
        0.0,
        0.0,
        1.0,
    ),
    scale: Vec3(
        1.0,
        1.0,
        1.0,
    ),
}
[game/src/player/attack.rs:40:9] direction * 10. = Vec3(
    3.208275,
    -0.0,
    -9.471377,
)
[game/src/player/attack.rs:40:9] transform = Transform {
    translation: Vec3(
        3.0986729,
        1.7161975,
        8.229811,
    ),
    rotation: Quat(
        0.0,
        0.0,
        0.0,
        1.0,
    ),
    scale: Vec3(
        1.0,
        1.0,
        1.0,
    ),
}
[game/src/player/attack.rs:40:9] direction * 10. = Vec3(
    3.208275,
    -0.0,
    -9.471377,
)
sweet sundial
#

might just be colliding with the player immediately, or with each other

#

can rule that out by listening to collisions or just setting the RigidBody Kinematic

late cape
little maple
#

the documentation says that tunneling is more likely with small objects but how small is "small"? If I have an object that tunnels through a wall.. if I scale up both the object and the wall so they're larger but proportionally the same would I still get the same tunneling problem?

sweet sundial
#

small relative to wall thickness and velocity

#

ccd & speculative collisions should prevent it for non-absurd velocities though

vestal minnow
#

with speculative collision or swept CCD this shouldn't be a problem

#

however you can still have objects pass through walls if other objects are pushing them hard enough, due to contact softness

torn folio
#

I can't figure out how I can wait for colliders to finish generating, a la how you can wait for assets to load. Is it possible at all?

latent vigil
torn folio
#

oh does it count as an asset?

latent vigil
#

(cannot check atm, just responded to this part "a la how you can wait for assets to load")

torn folio
#

Fair enough, thank you. I haven't been able to find the example, if someone else has a link that would be lovely

knotty thicket
torn folio
#

cool! thank you. If the collider is only attached once it is ready, then that's perfect, I can use that 🙂

knotty thicket
#

hwhoops

hallow mulch
#

I'm loading gltf assets in an avian3d project. I use ColliderConstructorHierarchy like it's done in the collider_constructors example. It completely kills my CPU 🙂

vestal minnow
#

Using a convex decomposition?

hallow mulch
#

The asset loads, and then it goes wild and i have to kill the process

#

it's a pretty large model but not that much

#

(a house)

vestal minnow
#

Yeah convex decomposition is extremely slow, in most game engines like Godot you do the decomposition in the editor, not at runtime. We're kinda limited here since Bevy's asset preprocessing situation isn't great

hallow mulch
#

I can upload the gltf model somewhere if needed

#

Ok

#

Is there another option ?

vestal minnow
hallow mulch
#

I'd love to work on that.

vestal minnow
# hallow mulch Is there another option ?

I believe some people have implemented it manually by running convex decomposition and then serializing the produced collider using serde, saving it to a file, and when running the game, you deserialize and create the collider(s) that way

hallow mulch
#

Nice.

#

Looking at ConvexDecompositionFromMeshWithConfig ...

#

"Parameters controlling the VHACD convex decomposition."

vestal minnow
#

Using ConvexHullFromMesh is also wayyy faster if you don't need concave colliders for the meshes in your scene

hallow mulch
#

Will try that.

#

Ok, it's slightly better

#

Can see the colliders

#

I'm spawning like 20 houses, it's painfully slow.

vestal minnow
#

Is this with the dev profile or in --release mode or with at least some build optimizations

#

dev profile with no optimizations is very, very slow, especially for stuff like this IME

hallow mulch
#

It's a custom profile.

#

I'll try in release mode.

#

There's just so many colliders generated for the platform ..

vestal minnow
#

mm 6.8k vertices for the model, potentially with 20 houses is quite a lot, though not like a crazy amount

#

but enough to most likely be slow to generate colliders at runtime

hallow mulch
#

But it's awfully slow even after all the houses and the colliders have been processed.

#

The debug plugin is activated, maybe that doesn't help ..

#

I'll use simpler models, really cool that avian supports this.

hallow mulch
torn folio
torn folio
viral goblet
#

Anything I could do to stop these from crashing the app?

cinder summit
#

NaN coordinates, weird rotations, or invalid shapes is the only causes I can think of ... All of which would crash elsewhere anyway 🤔

viral goblet
sand smelt
#

A neat trick is to use the track_location feature on bevy, which can tell you where the last write to a component happened. That allows you to do a debug system where you can query for NaNs and figure out who wrote it there

viral goblet
#

@sand smelt interesting
Although I never reduce velocity or assign to it manually, only add to it
So I don't understand how that could be possible

viral goblet
dry jolt
#

hiya. anything special todo when despawning and entity that hs colliders and such on it? im getting a collider crash when despawning some entitties..

#
cargo/git/checkouts/avian-5a22c167119f3550/567b9f5/crates/avian3d/../../src/collision/collider/mod.rs:512:9:
assertion failed: b.min.cmple(b.max).all()
plush mulch
#

How can I Check if my collider is grounded?

plush mulch
#

Ping me please

sweet sundial
#

...

#

@plush mulch

sweet sundial
#

interestingly, the return type from Collisions::collisions_with and its inner types all seem perfectly capable of impl'ing Copy, which would prevent a .collect() in that code

visual sparrow
vestal minnow
#

@maiden charm I'm curious which parts have the most overhead for your project, if you run with the PhysicsDiagnosticsPlugin and PhysicsDiagnosticsUiPlugin (requires the diagnostic_ui feature) 🙂

#

If there's a looot of colliders but not too many active collisions then I would suspect that the broad phase and maybe spatial query pipeline updates are the most costly currently

visual sparrow
vestal minnow
#

Yeah that should get fixed with the broad phase rework which I'm trying to finally get done now

visual sparrow
vestal minnow
visual sparrow
#

I recommend doing a cast_move into Vec3::NEG_Y * some_small_distance (e.g. 0.05)

#

if that hits, you're grounded