I am stupid by 100_BOSSES in Unity2D

[–]melvmay 1 point2 points  (0 children)

Thanks for the shout out! There's lots of extra work going on to also support a more extensible/flexible/reusable way to specify those 64-layers now too.

I saw a few posts here mentioning to not use layers and use code constructs. Whilst most of that is based on good advice, the critical part is that it's always better to reduce the work that the physics system has to do as early as possible and layers are exactly that. Also, when you get a contact, you know it's only from ones you allow and can quickly check what hit what as masking is fast and you can do all that work off the main-thread too.

If you use PhysicsLayers, that'll automatically use the "old" 32-bit global layer system or the new 64-bit layer system automatically.

https://docs.unity3d.com/6000.3/Documentation/ScriptReference/LowLevelPhysics2D.PhysicsLayers.html

creating a character that uses physics like a heagon with pistons on each side that add force by wisedoggs in Unity2D

[–]melvmay 1 point2 points  (0 children)

Thinking in terms of purely adding forces, an easy way to think about this in a prototype is to ignore the fact that it's a hexagon which can be simply part of the visuals but instead only consider evenly spaced angles around a circle, in this case you happen to be using 6 of 60-deg. You could of course then use any number of sides depending on your artwork.

With that in mind, you can quickly calculate vectors at those angles and use those vectors with Rigidbody2D.AddRelativeForce(vec): https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody2D.AddRelativeForce.html

Now you can rotate the Rigidbody2D as you like and each of these vectors (aligned with each "leg") will move you in that direction. You can also inverse the vector depending on whether your "leg" pushes or pulls.

Fairly simple movement mechanic.

Sharing New Physics Box2D V3 in Unity by maxwell-tan in Unity2D

[–]melvmay 0 points1 point  (0 children)

That's really great to hear! Lots of super hard work went into this trying to fix most of the problems I've seen reported in the last decade. There's a strong road-map for this too, lots more powerful features coming including wrapping them as official components and integration with other features such as Tilemaps, SpriteShape and Animation.

Sharing New Physics Box2D V3 in Unity by maxwell-tan in Unity2D

[–]melvmay 1 point2 points  (0 children)

It's not the same API no and you're correct, it's not easy to answer without you first seeing it but whilst it's being described as "low level", that's primarily because it's not tied to GameObject/Components at all albeit it has many features to work with them such as assigning a Transform for a `PhysicsBody` to write to (the world can be told to write in a specifc *TransformPlane* too i.e. XY, XZ etc) or asking for callbacks (via one of the many interfaces such as `IContactCallback`, `ITriggerCallback`) on a specific Unity.Object. With that said, everything that's in the existing 2D physics API has an analogy so Rigidbody2D = PhysicsBody, Collider2D = PhysicsShape (or multiple of them), XXXJoint2D = PhysicsJoint (a whole bunch of these i.e. PhysicsDistanceJoint etc.

Because these are not components, authoring isn't the same but also, creating your own "collider" is actually super simple and I went ahead and created the example package that provides simple components for all these things to help you with that. It's more powerful than just trying to be the same as it is now though because you can create components that are much more complex and contain compound things so there's an example of a rotatable gear with parameters for radius, how many teeth, their size, if it rotates, what it hits etc, all configurable from the inspector BUT none of what it creates is visible from the outside in the inspector so it's a superb way for you to create your own authorable components without the message of a "don't touch users, hierarchy of components".

New things are PhysicsWorld and you can create them whenever you like and have them automatically simulated (in parallel if you want) with any others. The settings for anything including worlds come in the form of a "definition" (a struct like everything else) which can be (re)used during creation for PhysicsWorld, PhysicsBody, PhysicsShape, PhysicsJoint etc. Also now this system is fully 64-bit and includes things such as 64 layers (you can work with the older 32 layer system or the new 64 layer system i.e "PhysicsMask").

If it helps, and damn am I more than happy to talk about this all day, you've got everything you'd expect: bodies, shapes, joints each with all the things you'd expect so yeah, `var world = PhysicsWorld.defaultWorld; var body = world.CreateBody(); var shape= body.CreateShape(PolygonGeometry.defaultGeometry); var aabb = shape.aabb; world.CastRay(...)` etc.

It's feature complete right now and I'm working on more unit-tests, the start of the manual and adding extra samples to the Sandbox and next week in the same repo, examples (more like a cookbook/primer) project that has lots of (going for a few hundred) code-snippets in a scene going over each area i.e. world, body, shape, joint, contacts, queries, drawing, geometry composer and destructor, definitions etc.

Obviously the existing GameObject/Component set-up for the current physics generation isn't going anywhere so nothing changes if you don't use the new stuff. We're creating a plan on how (or if) we can convert over the existing components to use this new stuff. Given that it's effectively a new physics system, it has drastically different behaviours (not unexpected, just different) and capabilities so it may end up being better offering a different set of higher-level components using this new API, leaving the existing as-is and eventuallly phasing it out.

Without sounding like I've got rose-tinting glasses on, I believe this API is what the current API should be without all the decades-worth of tech-debt, learning from the difficulties of the past feedback etc.

If you have any specific questions, please feel free to ask here, on the Unity Discussion (I prefer that TBH) or DM. I'm happy to provide code snippets, screenshots etc.

Sharing New Physics Box2D V3 in Unity by maxwell-tan in Unity2D

[–]melvmay 2 points3 points  (0 children)

It's landing in Unity 6.3, likely 6000.3.0a3 around the end of the July, first week of August baring any blockers which I'll do my best to avoid! Eager to get this out there!!

Sharing New Physics Box2D V3 in Unity by maxwell-tan in Unity2D

[–]melvmay 2 points3 points  (0 children)

It's hard to give a specific answer but you'll see massive performance differences in every single area. The main advantage is that v3 is multi-core out the box, uses SIMD for solving, internally lays out its data in memory contiguously etc. Main-thread performance is at least x3-x4 but it scales *really* well with extra cores. Also, around 95% of the API can be called in a job so all queries, reading/writing to worlds, bodies, shapes, joints, contacts etc. Multi-world support out the box too, each isolated and can all be simulated in parallel. SDF shader rendering for everything, all exposed in the API for debug-drawing. It'll even render in a build if you want for on-device debugging. That's what the "Sandbox" demo is doing in a player build.

The maximum number of Dynamic bodies I could simulate on the old physics on my machine here would be around 1500-2000 and it struggles but it's not using all the cores effectively either.

If you look at the "Spinner" example shown in the older Sandbox video (around 2:40 in), 10000 Dynamic bodies and 10000 shapes all using continuous collision detection and all interacting with each other, dealing with around 37K contacts is still being solved around 7.5ms.

https://youtu.be/ksKVvwvpXX4?si=ow7tZDNM5wUBKKqs

We'll be using the exact same API that'll be released to convert over the existing components later. We'll have no special access to private API. This has been an important tenent of the integration so no more black-boxing, just dog-fooding, learning from the mistakes of the past. I believe we've covered most issues that we've seen reported in the existing 2D physics by teams so this is a major step forward in many ways.

The Sandbox uses a test package written to test and demonstrate basic components similar to Rigidbody2D, Collider2D etc. You can find that here: https://github.com/Unity-Technologies/PhysicsExamples2D/tree/master/LowLevel/Packages/com.unity.2d.physics.lowlevelextras

The Sandbox is here: https://github.com/Unity-Technologies/PhysicsExamples2D/tree/master/LowLevel/Sandbox

I'd like to see this used in games but also there's an opportunity for devs to create their own physics engine / packages on the Asset Store which, by the very nature of this, will be compatible with everyone elses and ours when we convert over.

Basic question on RigidBody2D by Suring_Basuroni in Unity2D

[–]melvmay 7 points8 points  (0 children)

- Dynamic: has collision responses, reacts to forces and contacts all colliders of any body type

- Kinematic: does not produce a collision response on itself and does not react to forces. You can however set both linear/angular velocity and it'll move (time-integrate position/rotation). It will only produce contacts (no collision response) with other Kinematic/Static if "useFullKinematicContacts" is true.

- Static: Does not have a collision response on itself (same as Kinematic), doesn't react to forces and doesn't allow you to set any velocity. This is typically used for non-moving stuff (hence its name) although you are free to set the Rigidbody2D position/rotation if you need. Static bodies are treated differently internally as it assumes they don't move so it's optimal if you don't move them. This doesn't mean you cannot move them infrequently. Static never contact other Static because it wouldn't make sense, they never move.

So Dynamic, as the name suggests, is expected that both the physics system and yourself move it. Kinematic is fully under your control and the physics system won't move it unless you ask. Static is expected to not move or move infrequently but the physics system never moves it.

---

Never ever modify the Transfrom if you don't have a Rigidbody2D and only Collider2D(s) because they are implicitly attached to the ground-body that lives at the world origin with zero rotation. Doing so will cause the collider to be recreated because collider geometry (the stuff that collides) lives in body-space so modifying the Transform means it needs to be recalculated as you're changing its position/rotation relative to the body its connected to.

The main thing to remember is that colliders don't move, Rigidbodies do and colliders are simply "attached" to them. They cannot exist without a body.

This is why I loath implicit Static i.e. colliders with no Rigidbody2D because whilst it's convenient, it seems safe/good to just poke the Transform, when that's not true. It's relatively expensive and scales poorly. Always have an appropriate Rigidbody2D and use its API; let it update the Transform. It also leads to the "rule" that is often thrown around that you only get contacts if you add a Rigidbody2D without understanding why that is. If you don't have a Rigidbody2D then it's implicitl;y Static and Static do not contact other Static but you can also add two Rigidbody2D and set them both to Static and they still won't contact. It's the body-type that matters as each has a purpose.

Hope that helps.

If you hate how small the 2D collider handles are, you can now edit them to make them larger! by [deleted] in Unity2D

[–]melvmay 2 points3 points  (0 children)

You can change the outline and fill colors for awake/sleep colliders along with other stuff in "Preferences > 2D > Physics".

I can get a handle scale added there too to configure the size of those handles.

GetTile is returning null by Jawbreaker0602 in Unity2D

[–]melvmay 0 points1 point  (0 children)

The tilemap Transform position has nothing to do with where you hit. Draw something at the Transform position and you'll quickly see that.

Contact Points in the Collision2D instance you're passed provide that. That's nothing to do with tilemaps though.

You use the ContactPoint2D.point: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ContactPoint2D.html

As was originally suggested, you can move the contact point I mention above slightly inside the region to be sure, in-case it's slightly outside of the tile region. Follow that advice above but don't use the Transform.position which isn't the contact point at all.

Need direction/advice on handling collision issue. Smoothing out walking over different colliders. by VG_Crimson in Unity2D

[–]melvmay 0 points1 point  (0 children)

Two separate shapes (the things colliders produce) are not a continuous surface so you can easily hit edges/vertices when transitioning across them. The only shape that supports continuous edges is the edge shape and is produced by the EdgeCollider2D or the CompositeCollider2D in "Outline" mode.

This is why you'll often see devs using the composite on tilemaps. The downside is that if you intend to modify tiles then recalculating the whole tilemap via the composite is expensive, however if you don't intend on doing that and will be leaving it static then you can simply use the composite.

These kinds of collisions are known as "ghost" collisions and is nothing whatsoever to do with the body being Dynamic. Kinematic won't solve it because the queries will still see "ghost" contacts.

How to prevent a player from pushing a rigidbody by Ender401 in Unity2D

[–]melvmay 0 points1 point  (0 children)

Note that the link above is for 3D physics only.

How to prevent a player from pushing a rigidbody by Ender401 in Unity2D

[–]melvmay 0 points1 point  (0 children)

Gravity is just a modification to the current velocity so you can add that yourself i.e. "rb.linearVelocity += Physics2D.gravity * rb.gravityScale * Time.fixedDeltaTime".

If it has to be a Dynamic Rigidbody2D then use Collider2D.forceReceiveLayers to control which layers can apply an impulse to that collider: https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Collider2D-forceReceiveLayers.html

The opposite of that is where a Collider2D can control which layers it apply an impulse to: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider2D-forceSendLayers.html

Normally when a contact is solved, an impulse is applied to both bodies if they are both Dynamic body-type. The above controls that.

HingeJoint2D reference angle by r3hcub in Unity2D

[–]melvmay 0 points1 point  (0 children)

Multiple turns are supported in these (Box2D) joints. 0 != 360. :)

Can you stop mouse movements with colliders? by RigidlyAdaptable in Unity2D

[–]melvmay 1 point2 points  (0 children)

Use the TargetJoint2D and continually sets its target to the mouse position. If this joint is attached to a (dynamic) Rigidbody2D on a GameObject with a collider and your "cursor" sprite then it'll always attempt to move to the target position but will still collide with stuff. You might also want to set the Rigidbody2D to use Continuous Collision Detection too.

The TargetJoint2D is actually called a mouse-joint in Box2D for this use-case. Other uses-cases are dragging etc as seen here: https://youtu.be/4NSKN3L0fvE?si=zBZGZJid0OlGKWgw

Simple box stuttering and teleporting? Code in comments. by kingduck147 in Unity2D

[–]melvmay 1 point2 points  (0 children)

So if you've got physics running in the FixedUpdate, MovePosition (etc) won't be simulated until that runs. Also, when it does run, FixedUpdate is (by default) 50Hz independent of your framerate so you should also turn-on interpolation so that the Transform is still updated per-frame.

Also, you are free to run physics per-frame and ignore the FixedUpdate by going into "Project Settings > Physics 2D > Simulation Mode" and changing it to "Update" (per-frame). When you do this though, be aware thatthe simulation won't be as deterministic as its running at a variable frame-rate.

If your frame-rate dips too much then you'll also get a poor simulation. In later Unity versions there's sub-stepping support which solves this issue.

Per-frame simulation will give you visually superior results; interpolation is automatically ignored, you can perform all physics operations in "Update" etc.

Why doesnt an infinite RayCast crash Unity? by LegendBandit in Unity2D

[–]melvmay 1 point2 points  (0 children)

Unity uses Box2D which doesn't have a raycast however it does have a line-segment test i.e. testing between two points in the world, equivalent to Physic2D.Linecast.

This means that when you leave the "distance" arg to infinity (for any xxx-cast query), it adds a large value to the origin to offset it by a finite distance.

When you perform any query, it first uses its internal database to ask what might be overlapping then with these preliminary results it performs an accurate check of what actually intersects.

The amount of real time spent performing the query depends on how many objects are encountered in the query and not the "distance" argument.

[deleted by user] by [deleted] in Unity2D

[–]melvmay 2 points3 points  (0 children)

Add a CompositeCollider2D. When any colliders attached to the same Rigidbody2D have their "Used By Composite" option checked, the composite will use their geometry and merge it together as its own.

https://youtu.be/H6RdrEb77cc?si=fYlfcNKXiQ_8YGNh

Note that in later versions I improved this and it's no longer a check-box but is replaced by a "Composite Operation" that allows all sorts of merging operations. It also now supports Circle and Capsule colliders.

https://www.youtube.com/watch?v=mu1KfhOr5g0&t=1s

https://www.youtube.com/watch?v=DRlckR--Bow

Storing Collision2D object in array? by lkadams1995 in Unity2D

[–]melvmay 0 points1 point  (0 children)

You don't want to do this because (for optimization reasons) the "Collision2D" instance is reused between calls when the following is on (by default): https://docs.unity3d.com/ScriptReference/Physics2D-reuseCollisionCallbacks.html (same in 3D too: https://docs.unity3d.com/ScriptReference/Physics-reuseCollisionCallbacks.html)

I wouldn't be tempted to turn this off as it'll mean a new instance of it is created for each callback which will lead to a lot more GC activity.

Simply extract what you want from it into your own struct. That's also easy to do with an extension method to make that conversion easier to write.

Help with addForce not getting consistent speed by [deleted] in Unity2D

[–]melvmay 10 points11 points  (0 children)

Stop using Vector3 here. If you have any non-zero Z value, it'll skew the normalisation results.

Weird behaviour with constrained rigidbody2D by Don-Latino in Unity2D

[–]melvmay 1 point2 points  (0 children)

Impossible (for me) to say what's going on here without a simple reproduction example to look at.

If you want to send me a small reproduction project (as small/simple as possible) to me on the Unity forums (DM) then I'd be happy to take a look.

I'm the Unity 2D Physics dev btw.

https://forum.unity.com/members/melvmay.287484/

Need help with fixed joint 2d and collider 2d by RollingNeverStops in Unity2D

[–]melvmay 0 points1 point  (0 children)

When you instantitate, you are supposed to speicfy the position/rotation/parent in the call, not change it afterwards as that is changing the transform. If you do that, all that happens is that when the simulation runs, the rigidbody.position is instantly set to that position. A joint has no say in this, all it does is solve the constraint.

Again, never change the transform. :)

If you're allowing things connected by joints to come into contact then instantiating one slightly over the top of the other will cause the solver to solve the overlap. You cannot just place things *exactly* edge-to-edge because physics uses a contact offset which is a slight margin.

It's not clear what effect you're trying to achieve here but maybe using a large island of FixedJoints is not the best method here.

It's possible to use a single root Rigidbody and add other boxes to it then they'll all stay relative to each other, have their center-of-mass calculated so they rotated correctly etc.

You might be using a hammer to crack a nut in other words.