Search Unity

Official Unity Physics Discussion

Discussion in 'Physics for ECS' started by smcclelland, Mar 18, 2019.

Thread Status:
Not open for further replies.
  1. WAYNGames

    WAYNGames

    Joined:
    Mar 16, 2019
    Posts:
    992
    Hello,
    I Need some heelp with the conversion workflow. How would one get the reference to an entity on another entity from the inspector.

    Setup :
    In my hierarchy i have two game objects A and B both with the convert to entity component. Now I had a proxy to the game object A and add a serialized field of type game object. In the inspector I populate this field with the game object B.

    Goal :
    When converting A I want to set the Entity created by the convertion of B inside a custom component data on A.
     
    Last edited: Apr 28, 2019
  2. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    Use this thread please: https://forum.unity.com/threads/new-subscene-converttoentity-workflows.638785/
     
  3. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    333
    Is this the right place to be reporting bugs for this?

    Having an entity with just a translation, rotation, collider, and velocity is throwing an exception in
    BuildPhysicsWorld
    . The CreateMotions job is failing.

    Code (CSharp):
    1. IndexOutOfRangeException: Index 0 is out of range of '0' Length.
    2. Unity.Collections.NativeArray`1[T].FailOutOfRangeError (System.Int32 index) (at C:/buildslave/unity/build/Runtime/Export/NativeArray/NativeArray.cs:207)
    3. Unity.Collections.NativeArray`1[T].CheckElementReadAccess (System.Int32 index) (at C:/buildslave/unity/build/Runtime/Export/NativeArray/NativeArray.cs:113)
    4. Unity.Collections.NativeArray`1[T].get_Item (System.Int32 index) (at C:/buildslave/unity/build/Runtime/Export/NativeArray/NativeArray.cs:138)
    5. Unity.Physics.Systems.BuildPhysicsWorld+Jobs+CreateMotions.Execute (Unity.Entities.ArchetypeChunk chunk, System.Int32 chunkIndex, System.Int32 firstEntityIndex) (at Library/PackageCache/com.unity.physics@0.0.2-preview.1/Unity.Physics/ECS/Systems/BuildPhysicsWorld.cs:378)
    6. Unity.Entities.JobChunkExtensions+JobChunk_Process`1[T].ExecuteInternal (Unity.Entities.JobChunkExtensions+JobChunkData`1[T]& jobData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at Library/PackageCache/com.unity.entities@0.0.12-preview.30/Unity.Entities/IJobChunk.cs:135)
    7. Unity.Entities.JobChunkExtensions+JobChunk_Process`1[T].Execute (Unity.Entities.JobChunkExtensions+JobChunkData`1[T]& jobData, System.IntPtr additionalPtr, System.IntPtr bufferRangePatchData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at Library/PackageCache/com.unity.entities@0.0.12-preview.30/Unity.Entities/IJobChunk.cs:122)
     
    steveeHavok likes this.
  4. etiennepinchon

    etiennepinchon

    Joined:
    May 16, 2018
    Posts:
    8
    Thanks a lot man, absolutely makes sense. I played with the new workflow this afternoon, everything works perfectly (including Physics) and is really enjoyable to use. Love it!

    One more thing, do you know if Unity Physics will support mesh to mesh collision? In most cases the other collision types will do the trick however many will require mesh colliders in order to work.
     
  5. OmiCron07

    OmiCron07

    Joined:
    Jun 27, 2015
    Posts:
    7
    Please, check out my project. My capsule has little friction applied when I set the InverseInertia to 0 (in RotationLockProxy on the player). Start the SampleScene.
     

    Attached Files:

  6. Buretto

    Buretto

    Joined:
    Mar 23, 2015
    Posts:
    49
    Hi, is there a way to re-size a collider at runtime without creating a new one? For instance, if I change the Scale component, I would like the collider to also scale along with the mesh. Or right now, is it my best bet to just re-create the collider with new size value?
     
    steveeHavok and Orimay like this.
  7. CSampson

    CSampson

    Joined:
    Apr 24, 2019
    Posts:
    7
    Anyone know how I would constrain/lock axes from movement and rotation with Unity Physics for ECS
     
  8. WAYNGames

    WAYNGames

    Joined:
    Mar 16, 2019
    Posts:
    992
    Something like that :
    Code (CSharp):
    1. using Unity.Entities;
    2. using Unity.Jobs;
    3. using Unity.Transforms;
    4. using Unity.Collections;
    5. using Unity.Mathematics;
    6. using Unity.Burst;
    7.  
    8.     public class LockRotationSystem : JobComponentSystem
    9.     {
    10.  
    11.         [BurstCompile]
    12.         [RequireComponentTag(typeof(LockRotationTag))]
    13.         struct LockRotationJob : IJobForEach<Rotation>
    14.         {
    15.              public void Execute(ref Rotation rotation)
    16.             {
    17.                 rotation.Value = quaternion.identity;
    18.             }
    19.  
    20.         }
    21.  
    22.         protected override JobHandle OnUpdate(JobHandle inputDependencies)
    23.         {
    24.             return new LockRotationJob().Schedule(this, inputDependencies);
    25.         }
    26.      
    27.  
    28. }
    where LockRotationTag is just an empty component to identify which entity to lock.
    same thing with Translation instead of Rotation for position lock.

    You can also act on PhysicsVelocity if you want (linear for mouvement, and angular for rotation)
     
  9. CSampson

    CSampson

    Joined:
    Apr 24, 2019
    Posts:
    7
    Thankyou,
    If i act directly on Rotation will it mean the physics system will be out of sync with the rotation of the actual entity?
     
  10. WAYNGames

    WAYNGames

    Joined:
    Mar 16, 2019
    Posts:
    992
    The physics system do not store the position and rotation data. It act on them through it's own data, namely the physics velocity.
    Rotation and translation are the space representation. And physics is the force applyed to those space representation.
    Hope I make sense.
     
  11. CSampson

    CSampson

    Joined:
    Apr 24, 2019
    Posts:
    7
    Cool yep thx
     
  12. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    333
    I talked with @steveeHavok about this further up the thread starting here. His main replies with code samples are here and here.

    There are a few different ways you can do this. The way mentioned by @WAYN_Group might work fine for some things but it's not physically accurate. The solver won't know about the constraint, so in a collision it might try to push the object in the constrained axis. If your system resets that to lock it then the energy in that axis will be lost, and you won't have momentum conservation in your simulation.

    It's better to use a constraint. There are a few different ways to do that. I've found that joints are the most robust and flexible way at the moment, but @steveeHavok outlines a few different options in that discussion.
     
    WAYNGames likes this.
  13. WAYNGames

    WAYNGames

    Joined:
    Mar 16, 2019
    Posts:
    992
    Thanks for the links. I'll try using inertia and joints to see the difference.:)
     
  14. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Is there any way you could get me a repro of this crash? We haven't seen it happen locally.
     
  15. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    333
    @WAYN_Group I want to illustrate because I'm not sure that I was clear. Imagine a 45 degree collision like so where the ball changes direction by 90 degrees. We want to constrain the movement to be only horizontal. This diagram uses 2D and 1D for simplicity but the same goes for 3D and 2D.

    If we zero the vertical component as you suggested the ball would simply stop when it collides, because it would try to go up and you would stop it.

    If we constrain the vertical motion for the solver by using joints or similar, it will bounce back to the right and ignore the existence of the vertical axis, as if it had hit a vertical wall.
    upload_2019-4-30_14-16-28.png
     
  16. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    333
    Oh I thought it was happening in a brand new empty project, but I'll take a look at recreating.
     
  17. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Some of the convex primitives can be updated. For example the BoxCollider has the Center, Orientation and, to your question, Size parameters that you can change. Not all the colliders have these though. Mesh and ConvexHulls would really need re-created with new data. New demo needed so :)

    This snippet grabs the Collider from the PhysicsCollider component:
    Code (CSharp):
    1. fixed (Collider* collider = [PhysicsCollider]->ColliderPtr)
    2. {
    3.     switch (collider->Type)
    4.     {
    5.         ...
    6.         case ColliderType.Box:
    7.             var boxCollider = ((BoxCollider*)collider);
    8.             boxCollider.Size = new float3( x, y, z );
    9.             break;
    10.         ...
    11.         default:
    12.             break;
    13.     }
    14. }
    I'll leave you to worry about the thread safety issues that come from you changing the size while something else is trying to read it.
     
    Buretto likes this.
  18. WAYNGames

    WAYNGames

    Joined:
    Mar 16, 2019
    Posts:
    992
    Yep, understood thanks for the simple case.
     
    SamOld likes this.
  19. BanJaxe

    BanJaxe

    Joined:
    Nov 20, 2017
    Posts:
    47
    When using physics and ECS what steps are nessercary to ensure framerate independance?

    I've tried using [DisableAutoCreation] on physics related systems (ones that modify PhysicsVelocity components) and then manually calling Update on them from a monobehaviour in FixedUpdate(). Not sure if that is correct or not.
     
  20. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    333
    Fresh project in 2019.1.01f. Entities and physics packages added only.

    This is the sole code in the project and the scene is left as default.

    Code (CSharp):
    1. class BugSpawnerSystem : ComponentSystem
    2. {
    3.     protected override void OnUpdate()
    4.     {
    5.         var entity = PostUpdateCommands.CreateEntity();
    6.  
    7.         PostUpdateCommands.AddComponent(entity, new Translation());
    8.         PostUpdateCommands.AddComponent(entity, new Rotation());
    9.         PostUpdateCommands.AddComponent(entity, new PhysicsVelocity() { Linear = { z = 1 } });
    10.         PostUpdateCommands.AddComponent(entity, new PhysicsCollider() { Value = SphereCollider.Create(0, 1, CollisionFilter.Default) });
    11.     }
    12. }
    In reproducing the bug I've noticed some further behaviour. When setting the linear velocity to zero the same error is shown in the log but the entire editor freezes and I have to crash it. When setting z to 1 as shown it throws every frame but the editor responds fine. I've only reproduced the full freeze 3 times so it could be coincidence. One time when it fully froze, the error logged was an anonymous boolean assertion failure instead, but I wasn't able to read the full trace because the editor was frozen.

    Editing to add that burst is disabled.
     
    Last edited: Apr 30, 2019
    steveeHavok likes this.
  21. WAYNGames

    WAYNGames

    Joined:
    Mar 16, 2019
    Posts:
    992
    Ok, I played a little with the Joints and when applying a constraint on an axis if I have nothing as the referenced Connected Body it reset the axis to 0. I can't reference my own body it fails an assertion. The only way I could place the constraint and still keep my position and rotation was to add another Physics body as the child of the Game Object I want to constraint and refecent it on the Joint. Not fan of this.

    InvertInertia does the same thing without messing the initial position and rotation of the object.

    Still need to figure out the position lock...
     
  22. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    333
    Are you using the
    LimitDOFJoint
    ? You should have nothing as the referenced body, and it will constrain it in place where it is without resetting it to 0.
     
  23. WAYNGames

    WAYNGames

    Joined:
    Mar 16, 2019
    Posts:
    992
    Nop, just the angular one. Just tested the LimitDOFJoint but don't have the same behaviour with it...
    The LimitDOFJoint does not mess up the position and rotation but also don't seem to constraint them... I need to test this more
     
  24. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Thanks for that. Problem found. The issue is the moving body (i.e. has a PhysicsVelocity) doesn't have a PhysicsMass component and the engine is assuming (rather than checking or requiring) there is a PhysicsMass component on it as well. So can you add a PhysicsMass component? And if you do want a kinematic, rather than dynamic, body you can use the PhysicsMass.CreateKinematic instead of PhysicsMass.CreateDynamic static functions.
    Code (CSharp):
    1.         var colliderComponent = new PhysicsCollider() { Value = SphereCollider.Create(0, 1, CollisionFilter.Default) }
    2.         PostUpdateCommands.AddComponent(entity, colliderComponent);
    3.         PostUpdateCommands.AddComponent(entity, PhysicsMass.CreateKinematic(colliderComponent.MassProperties)
     
    SamOld likes this.
  25. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    505
    I solved it in the short term by setting bullets to dynamic and units to kinematic. That way I can just flip to kinematic when the fix version is out.

    But now I'm looking at using CalculateDistance to find the nearest enemy unit. With one unit and nothing else in the scene, the collider ends up finding itself. With two unit in the scene and nothing else, they both find one of the units, but always the same unit.

    Am I using it wrong?? I want each unit to find the closest enemy unit.

    Also when this is working, I don't know how to filter out the bullet colliders, don't want to find the closest bullet! The ColliderDistanceInput doesn't seem to accept a filter? Any suggestions?
    Code (CSharp):
    1.  
    2. private struct Job : IJobForEachWithEntity<Translation, Rotation, PhysicsCollider, NearestEnemy>
    3. {
    4.     [ReadOnly] public PhysicsWorld PhysicsWorld;
    5.     public void Execute(Entity entity, int index, [ReadOnly] ref Translation tran, [ReadOnly] ref Rotation rot, [ReadOnly] ref PhysicsCollider col, ref NearestEnemy nearestEnemy)
    6.     {
    7.         unsafe
    8.         {
    9.             ColliderDistanceInput input = new ColliderDistanceInput
    10.             {
    11.                 Collider = col.ColliderPtr,
    12.                 Transform = new RigidTransform(rot.Value, tran.Value),
    13.                 MaxDistance = nearestEnemy.QueryRange
    14.             };
    15.             DistanceHit hit;
    16.             PhysicsWorld.CalculateDistance(input, out hit);
    17.             nearestEnemy.Entity = PhysicsWorld.Bodies[hit.RigidBodyIndex].Entity;
    18.             Logger.Log($"nearestEnemy.Entity: {nearestEnemy.Entity}");
    19.         }
    20.     }
    21. }
    Cheers
     
  26. Brian-FJ

    Brian-FJ

    Joined:
    Apr 23, 2013
    Posts:
    9
    Hi, we're having a bit of trouble with chains of joints. We've modified the demo 4a Joint Parade and moved the free hinge so that we have several joints in a row that share the same axis. I would expect this line of blocks to be straight across but it's very easy to make them bow drastically. Either increasing the mass of the end object to 20 or scaling the blocks down to 0.2 size creates the bowing you see in the picture.

    Is there a work around we can do to fix this? I did see the comment about modifying the solver to pretend the inverse inertia is 0 on the axes we don't want movement but that won't work for us if it is for the entire simulation. Can we do that just for the interaction of a joint?

    Or is this something we expect to see improvements on in future releases?

    upload_2019-5-1_13-3-22.png
     
  27. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    505
    It looks like I fixed this with adjustments to the Physics Shape collision filter. The weirdness I described was poor collision filter setup on the game objects.

    But this is only in my scene with a couple of units and no bullets. I will keep working on this to figure out the best overall setup.

    But the use of the Physics Shape Collision Filter now means units can collide with units which is not what I am wanting. I think I can probably get what I need with the point version though using a custom filter.
     
    NotaNaN likes this.
  28. Brian-FJ

    Brian-FJ

    Joined:
    Apr 23, 2013
    Posts:
    9
    Just an update: I did take a look at this but I didn't have much luck. Setting the inverse inertia to 0 for the joint jacobians actually just meant the jacobian didn't apply any impulse and I can't see a reliable value to modify this with. Would you have any other suggestions to try?
     
  29. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    333
    Thanks, that's great and I had already added the mass to fix that, but I'm afraid I'm finding a whole class of similar bugs around nonstandard combinations of rigidbody components. It seems that it's quite easy to trip the engine up on bad assumptions.

    I tried to create a joint between a full dynamic rigidbody and an entity with only translation and rotation components. This seems to fail because it expects both to be rigidbodies. I'm unclear whether this should be allowed in the spec, but I would very much like it to be. The target of this joint should have none of the properties of a rigidbody other than that it determines a point about which another body should be constrained. It seems silly to have to give it things like mass and a collider when I only want it to determine a point in space. This currently throws two exceptions.

    Code (CSharp):
    1. Assertion failure. Value was False
    2. Expected: True
    3. UnityEngine.Assertions.Assert:IsTrue(Boolean)
    4. Unity.Physics.Systems.CreateJoints:Execute(ArchetypeChunk, Int32, Int32) (at Library/PackageCache/com.unity.physics@0.0.2-preview.1/Unity.Physics/ECS/Systems/BuildPhysicsWorld.cs:506)
    5. Unity.Entities.JobChunk_Process`1:ExecuteInternal(JobChunkData`1&, JobRanges&, Int32) (at Library/PackageCache/com.unity.entities@0.0.12-preview.31/Unity.Entities/IJobChunk.cs:135)
    6. Unity.Entities.JobChunk_Process`1:Execute(JobChunkData`1&, IntPtr, IntPtr, JobRanges&, Int32) (at Library/PackageCache/com.unity.entities@0.0.12-preview.31/Unity.Entities/IJobChunk.cs:122)
    7.  
    Code (CSharp):
    1. IndexOutOfRangeException: Index 16777215 is out of range of '4' Length.
    2. Unity.Collections.NativeArray`1[T].FailOutOfRangeError (System.Int32 index) (at C:/buildslave/unity/build/Runtime/Export/NativeArray/NativeArray.cs:207)
    3. Unity.Collections.NativeArray`1[T].CheckElementReadAccess (System.Int32 index) (at C:/buildslave/unity/build/Runtime/Export/NativeArray/NativeArray.cs:113)
    4. Unity.Collections.NativeArray`1[T].get_Item (System.Int32 index) (at C:/buildslave/unity/build/Runtime/Export/NativeArray/NativeArray.cs:138)
    5. Unity.Physics.Scheduler+CreateDispatchPairPhasesJob.FindFreePhase (System.Int32 bodyAIndex, System.Int32 bodyBIndex) (at Library/PackageCache/com.unity.physics@0.0.2-preview.1/Unity.Physics/Dynamics/Simulation/Scheduler.cs:734)
    6. Unity.Physics.Scheduler+CreateDispatchPairPhasesJob.Execute () (at Library/PackageCache/com.unity.physics@0.0.2-preview.1/Unity.Physics/Dynamics/Simulation/Scheduler.cs:605)
    7. Unity.Jobs.IJobExtensions+JobStruct`1[T].Execute (T& data, System.IntPtr additionalPtr, System.IntPtr bufferRangePatchData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at C:/buildslave/unity/build/Runtime/Jobs/Managed/IJob.cs:30)
    8.  
    In trying to remedy this I experimented with adding physics components to the target to get it recognised as a body. Adding only a sphere collider to the target (to make it translation, rotation, collider only) results in a different exception. This is hitting an
    Assert.IsTrue(false);
    in the code, so definitely shouldn't be happening.

    Code (CSharp):
    1. Assertion failure. Value was False
    2.  
    3. Expected: True
    4. UnityEngine.Assertions.Assert:IsTrue(Boolean)
    5. Unity.Physics.Solver:GetMotionVelocities(BodyIndexPair, NativeSlice`1&, MotionVelocity&, MotionVelocity&) (at Library/PackageCache/com.unity.physics@0.0.2-preview.1/Unity.Physics/Dynamics/Solver/Solver.cs:288)
    6. Unity.Physics.Solver:Solve(NativeSlice`1, Reader&, Writer&, Writer&, Int32, StepInput) (at Library/PackageCache/com.unity.physics@0.0.2-preview.1/Unity.Physics/Dynamics/Solver/Solver.cs:623)
    7. Unity.Physics.SolverJob:Execute(Int32) (at Library/PackageCache/com.unity.physics@0.0.2-preview.1/Unity.Physics/Dynamics/Solver/Solver.cs:145)
    8. Unity.Jobs.ParallelForJobStruct`1:Execute(SolverJob&, IntPtr, IntPtr, JobRanges&, Int32) (at C:/buildslave/unity/build/Runtime/Jobs/Managed/IJobParallelFor.cs:43)
    9.  
    I can try to put together a repro if needed, but I think these should be trivially reconstructed from my descriptions. These are using the new preview.31 of the entities package.
     
    steveeHavok likes this.
  30. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Ah, I think this is the same issue that others were having with raycasts hitting the body that the ray segment originated from. So, its 'correct' that asking what bodies are hit during CalculateDistance includes yourself but its not helpful. The issue is logged and we are looking into an option to ignore the initial overlap. If you haven't already seen it I recommend checkout the discussion that ended with this post : https://forum.unity.com/threads/unity-physics-discussion.646486/page-7#post-4474762
     
    Shinyclef likes this.
  31. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Fantastic work. Thanks for this. I will log these, check out some cleaner handling of these cases and add some more unit tests.
    There are definitely combinations we have tried yet but here was the assumption hierachy:
    • Adding a Translation, Rotation, and PhysicsCollider component makes an entity part of the physics world as a static rigid body
    • Adding a PhysicsVelocity component makes that Entity movable by physics, though it will have infinite mass
    • Adding a PhysicsMass component allows you to set a finite mass so it can react to collisions with other bodies
    • Adding a PhysicsDamping, PhysicsCustomData or PhysicsGravityFactor etc is for further tweaking
    This is why the joint connected to an entity with only Translation and Rotation failed - it won't have been added to the physics world. That said, trying to do that should probably be handled more cleanly.
    There is a default static rigid body added to the physics world. So your Joint can just set EntityA to be Entity.Null and we handle the rest - why even create an entity with only Translation and Rotation?
     
    SamOld likes this.
  32. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    This is a feature of an general iterative constraint solver. The bigger the mass ratio between the start of the chain and the end, the worse the bow. You can do a few things to help:
    • make things less heavy as you move out from the fixed object
    • increase the 'Solver Iteration Count' (in the heirarchy check out the 'Physics Step' component on the 'Physics Scene Basic Elements>Physics Setting' gameobject)
      • this lets the solver do more work in finding the correct positions by does cost more in CPU usage
    • add extra supporting Joints between the fixed body and the bodies at the end of the chain.
      • that said, unfortunately this can't be setup in the editor at the moment as multiple components cannot be converted e.g you will hit something like 'GameObject 'FreeHinge1 (3) (UnityEngine.GameObject)' has multiple FreeHingeJoint components and cannot be converted, skipping.'
      • you can do this in your own behavior though, as behind the scenes we actually create a new entity for each joint to bypass the problem at the ECS level.
      • this definitely needs to be fixed as multiple Joints between bodies is common
    Hope that all makes sense and helps. What is your actual use case for needing a free hanging joint chain like this?
     
    SamOld likes this.
  33. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    333
    Thanks. In my real scenario I have custom components on it as well that aren't part of the physics. My gameplay systems move it around in space. Essentially it's a kinematic body, but it collides with nothing, shouldn't show up in any spatial queries, and has no concept of shape or volume; so giving it a
    PhysicsCollider
    isn't quite right. It's part of a tethering and grappling system.

    I could emulate this with
    Entity.Null
    by recreating/modifying the joints every frame to reflect the targets' new positions, but that's messy and unnecessary work that it feels like the engine should be able to do for me.

    On a related note, I'd also suggest that the engine should integrate
    PhysicsVelocity
    even without a collider. I've done this myself for now by adding a parallel integrator. I'd also like to see
    PhysicsVelocity
    renamed to
    Velocity
    and moved into the core entities package to sit alongside
    Translation
    and
    Rotation
    .

    Velocity is a common property of objects, even outside of the physics engine. I often find myself wanting to read the velocity of an object in another system. As an example, I am prototyping a system that makes an entity leave a trail of particles when it moves. If I have a separate component to determine the velocity of non physics entities, then any system that reads velocity must have two distinct versions of the query, one for physics velocity and one for non physics velocity. I would prefer that there be a single core ECS component that can be considered the owner of the velocity property, and that any other system can rely on.
     
    steveeHavok and thelebaron like this.
  34. sebas77

    sebas77

    Joined:
    Nov 4, 2011
    Posts:
    1,643
    Hello there,

    I am not sure the problem is actually the bowing, as far as I understood, the problem is that the rotation of the hinge is not constrained to one axis only as a hinge should be. Tomorrow Brian will correct me if I am wrong. However while the bowing makes sense on a chain of hinges, I am not sure why the same problem applies to the constrained joints, including the rigid joints
     
  35. Brian-FJ

    Brian-FJ

    Joined:
    Apr 23, 2013
    Posts:
    9
    Thanks for the reply Stevee. The free hanging isn't actually in our use case but joint chains are. We want to create a physics sandbox where players can place axels, hinges and springs and we can power some of them. Besiege is a good example. We also want this networked so we're interested in a deterministic rollback approach and so far the determinism seems really good but the joint stability is worrying us.

    An example of something we'd like to create is is a truck with a trailer (joined with a hinge) with a rotatable digger on the back (so another hinge vertical), an articulation hinge and a grabber at the end. We've found that we can create this quite well with PhysX but then there is no rollback deterministic physics.

    I've attached a gif of the sort of thing you can create (this is working well although those hinges to the left are swaying a lot). You can see more examples at https://www.youtube.com/channel/UCxxXoaDlk1SykCWkX0RHePg

    I'm going to try adding multiple joint components across the rigidbody, that may help.

    I know things are very early but any idea about a time line for this? Don't mean to pester, really loving what I've seen so far with Unity Physics!
     

    Attached Files:

    SamOld and steveeHavok like this.
  36. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Ahh, I get you now. The dangling example in your gif makes the point well and is surprising. I'll log an issue and create a few test cases. There may well be a bug.

    While the editor can't convert multiple componets, you can probably get what you need going right now if you want to create your own custom Multi/Chain/WhateverJoint. Until we can all decide on the best approach before adding the code to the Authoring section of the Unity Physics package, the Joint Creators and Conversion code is just part of the demos at the minute.

    If you look in RagdollJoint.cs you will see that the RagdollJoint.Create function actually creates 2 Joint Entities. You could code up your own custom Joint behaviour to create as many sub-Joints as you need (e.g. automatically adding an extra joint between the initial body and the final body of a chain).
    Then in PhysicsJointConversionSystem.cs add your new Multi/Chain/WhateverJoint to the OnUpdate function.

    Hope this helps. I will get back to you on the Hinge issue.
     
    SamOld likes this.
  37. BanJaxe

    BanJaxe

    Joined:
    Nov 20, 2017
    Posts:
    47
    After some more testing I can't find any way to make the physics framerate independant. Higher fps makes the physics run faster. Not sure if this is a bug or I'm misunderstanding something?
     
  38. WAYNGames

    WAYNGames

    Joined:
    Mar 16, 2019
    Posts:
    992
    Simulation group system in wich you should run your systems acting on physics have been temprarly mouved to the end of uptdate in the player loop. It will be moved back to a fixed update when unity figure out some issues.

    Read this from a unity member post in this thread I think (at least on this forum)

    For my simple use cases I levrage vsync to cap it at 60 fps making the update effectively constant.
     
  39. WAYNGames

    WAYNGames

    Joined:
    Mar 16, 2019
    Posts:
    992
  40. eterlan

    eterlan

    Joined:
    Sep 29, 2018
    Posts:
    177
    Thanks for all your work! Little complain though.. Physics.Aabb & Math.AABB seems very similar but they have different way to construct, AABB use center & extent, Aabb use min & max. And there is neither implicit conversion nor hint about that. The only way to know their difference is by searching their implementation. It's not a big deal at this stage, just want to say it's not very intuitive. BTW the Jeep is very fun to play.:p
     
    steveeHavok likes this.
  41. DavidSWu

    DavidSWu

    Joined:
    Jun 20, 2016
    Posts:
    183
    Handling long chains of coupled rigid bodies is going to bad for a Gauss-Seidel solver with full coordinates*. Plus without sleeping your players will not be able to build much before the simulation costs get too high, even if some of the systems have a natural static equilibrium and are detached from what the player is currently building.
    To make player built dynamics systems work, you want:
    - At least a preconditioned solver, the current solver will need a lot of iterations to handle a highly coupled system, off the top of my head I cannot remember the convergence qualities, but I believe that the number of iterations required will be at least quadratic in the number of joints+degress of freedom. I.e. increasing the number of blocks 4 fold will increase the number of iterations that you need to reduce the error to given tolerance will be 16x the iterations. (assuming a constant number of joints per rigid body to hold it in place). If all bodies are interconnected, the iterations will be O(N!) or at least algebraic.
    - A system that converts connected bodies into fewer physics bodies that have appropriate degrees of freedom to represent the original setup. (unfortunately, the system only supports 6 DOF rigid bodies last I checked but that might change)
    - Most reduced coordinate algorithms (i.e. Featherstone) cannot efficiently handle arbitrarily closed loops, so you will still need a few joints to represent the original configuration.
    - You need things to sleep. If the player builds stuff that has a static equilibrium, you don't want to simulate it each frame. Without sleeping you cannot easily scale.

    *to be fair, it will be bad for any solver, but GS has particularly bad convergence when dealing with highly coupled systems.
     
    sebas77 likes this.
  42. eterlan

    eterlan

    Joined:
    Sep 29, 2018
    Posts:
    177
    Find a strange thing, the CollisionWorld.OverlapAabb(input, ref AllHits) doesn't care about CollisionFilter inside of input.

    I have a collectionSystem, and I want to collect apple around player using OverlapAabb, however, every time I collect player himself, which is weird. I use IsCollisionEnabled to test the CollisionFilters of input & Player, and the result is false. And I dig into the implement in BoundingVolumeHierarchy.cs, there is nothing deal with CollisionFilters. Everything else works fine, so I'm wondering is it as design or a bug?
     
    steveeHavok likes this.
  43. zephyr831125

    zephyr831125

    Joined:
    Mar 4, 2017
    Posts:
    54
    Hi, I found a problem when UnityPhysic + New Hybrid workflow.
    I have a prefab attached with a capsule PhysicsShape+PhysicsBody as collider, and a child with another big cylinder PhysicsShape as a enemy detect trigger.
    upload_2019-5-6_20-47-53.png
    I put it directly inside the scene and add ConvertToEntity on it, and Instantiate another one at runtime with a Script.

    With the first way, it has both PhysicShapes and hierarchy structure. The problem is the second way, the child cylinder PhyicShapes detached like this, and it don't move with the parent:
    upload_2019-5-6_20-50-36.png

    Here is my code of instantiating, very simple:

    Code (CSharp):
    1.  
    2. public class CreatePlayer : MonoBehaviour
    3. {
    4.     public GameObject Prefab;
    5.     // Start is called before the first frame update
    6.     void Start()
    7.     {
    8.         Entity prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, World.Active);
    9.         var entityManager = World.Active.EntityManager;
    10.      
    11.         entityManager.Instantiate(prefab);
    12.     }
    13. }
    14.  
    And I attached the whole project zip here.
     

    Attached Files:

  44. Adam-Mechtley

    Adam-Mechtley

    Administrator

    Joined:
    Feb 5, 2007
    Posts:
    290
    Thanks! I will take a look. It may be related to some things I am fixing right now.
     
    FROS7 likes this.
  45. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Yeah, there are a few pieces like that in Unity.Physics that should probably be consolidated and live in Unity.Mathematics.
     
    Orimay and FROS7 like this.
  46. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Thanks, thats logged and being looked into. It sounds like something we missing on that query. (i.e. bug :))
     
    eterlan and Shinyclef like this.
  47. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    Getting some very weird results from collider.CalculateAabb

    upload_2019-5-8_15-48-0.png
    upload_2019-5-8_15-48-33.png

    Job looks like this

    Code (CSharp):
    1. public void Execute(
    2.     Entity entity,
    3.     int index,
    4.     [ReadOnly] ref PhysicsCollider physicsCollider,
    5.     [ReadOnly] ref LocalToWorld localToWorld,
    6.     ref Observable observable)
    7. {
    8.      var position = localToWorld.Position;
    9.  
    10.     var collider = physicsCollider.Value.Value;
    11.     var aabb = collider.CalculateAabb(new RigidTransform(quaternion.identity, position)); // I am using rotation I just stripped it out for debugging.
    12.     // breakpoint
    13.  
    Physics shape setup looks like this

    upload_2019-5-8_15-50-8.png

    Simple 1x1x1 static box collider.

    Any ideas? It was working for a day then i made some comment changes and after a recompile started spitting garbage.

    -edit-

    This is the problem

    Code (CSharp):
    1. var collider = physicsCollider.Value.Value;
    2. var aabb = collider.CalculateAabb(new RigidTransform(quaternion.identity, position));
    This works fine

    Code (CSharp):
    1. var aabb = physicsCollider.Value.Value.CalculateAabb(new RigidTransform(quaternion.identity, position));
    I guess the blob ref makes a huge difference.
    Unintuitive.
     
    Last edited: May 8, 2019
    steveeHavok and rz_0lento like this.
  48. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    505
    Hello,

    I'm trying to use the CalculateDistance function to get the nearest 'enemy ship' collider.
    I specified collision layers:

    Ships: Applied to ships. Ships collide with raycasts and bullets (without raycast it doesn't work... why is it needed here...)
    Bullets: Applied to bullets. Bullets collide with ships.
    Raycasts: (Applied to nothing, used in below query).

    The results feel quite weird. Ships end up target bullets, but only momentarily. They soon after target enemy ships if they are found (i do the query every 0.2 sec). When no enemy ships are present, sometime all ships will find the same bullet even though there are some closer.

    My theory is that perhaps with the order of my systems, the physics system hasn't yet run on newly spawned bullets to do some kind of work with flags that would prevent them from being noticed, then they are not found on subsequent simulation iterations? Just a guess...

    I'm any case, just reporting thay it's all a fair bit odd to use currently with pretty unpredictable results.

    Code (CSharp):
    1. [BurstCompile]
    2.     private struct NearestCastJob : IJobForEachWithEntity<Translation, PhysicsCollider, NearestEnemy>
    3.     {
    4.         public float Time;
    5.         [ReadOnly] public CollisionWorld CollisionWorld; // I tried PhysicsWorld as well. What's the dif??
    6.  
    7.         public void Execute(Entity entity, int index, [ReadOnly] ref Translation tran, [ReadOnly] ref PhysicsCollider col, ref NearestEnemy nearestEnemy)
    8.         {
    9.             if (Time - nearestEnemy.LastRefreshTime < MinUpdateInterval)
    10.             {
    11.                 return;
    12.             }
    13.  
    14.             unsafe
    15.             {
    16.                 CollisionFilter filter = new CollisionFilter
    17.                 {
    18.                     CategoryBits = 1u << (int)PhysicsLayer.RayCast, // (int)PhysicsLayer.RayCast == 0
    19.                     MaskBits = 1u << (int)PhysicsLayer.Ships, // (int)PhysicsLayer.RayCast == 1
    20.                     GroupIndex = col.ColliderPtr->Filter.GroupIndex // entities (ships and bullets) on the same team share the same negative int
    21.                 };
    22.              
    23.                 PointDistanceInput pointInput = new PointDistanceInput
    24.                 {
    25.                     Position = tran.Value,
    26.                     MaxDistance = nearestEnemy.QueryRange,
    27.                     Filter = filter
    28.                 };
    29.  
    30.                 DistanceHit hit;
    31.                 CollisionWorld.CalculateDistance(pointInput, out hit);
    32.  
    33.                 Entity hitEntity = CollisionWorld.Bodies[hit.RigidBodyIndex].Entity;
    34.                 if (hitEntity == entity ||
    35.                     CollisionWorld.Bodies[hit.RigidBodyIndex].Collider->Filter.GroupIndex == col.ColliderPtr->Filter.GroupIndex) // TODO: REMOVE THIS TEMPORARY CASE WHEN THEY FIX THE FILTER!)
    36.                 {
    37.                     nearestEnemy.Entity = Entity.Null;
    38.                 }
    39.                 else
    40.                 {
    41.                     nearestEnemy.Entity = CollisionWorld.Bodies[hit.RigidBodyIndex].Entity;
    42.                 }
    43.  
    44.                 nearestEnemy.LastRefreshTime = Time;
    45.                 //Logger.Log($"{entity} found {nearestEnemy.Entity}.");
    46.             }
    47.         }
    48.     }
     
  49. WAYNGames

    WAYNGames

    Joined:
    Mar 16, 2019
    Posts:
    992
    Hi, i'm trying to make something like the survival shooter tutorial with DOTS. So far I can move and shoot bullets (sphere entity spawned each time).
    I was wondering if there were any sample of how to handle collision events and/or trigger.
     
  50. rz_0lento

    rz_0lento

    Joined:
    Oct 8, 2013
    Posts:
    2,361
Thread Status:
Not open for further replies.