Setting rigidbody.position sometimes doesn't change the position

The point of the code:
I have this code that shatters glass using a fracture pattern

The problem:
I have noticed a problem a while back where, sometimes when I shoot the glass and thus trigger the code, the new shattered glass doesn’t get it’s position changed to where it should be when I change the rigidbody.position. This seems to happen no matter the isKinematic value as well.
Also, the code creates many pieces, and when this issue happens, it happens to every one of them which leads me to believe it could have to do with timing. I have also noticed that when adding both of the Debug.Log()s in the code the issue stops appearing.

The rigid body (in case it matters):
rigidbody.interpolation = RigidbodyInterpolation.Extrapolate;
rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;

The code:
I am not gonna post the full code as long as not requested as I believe this includes everything important, but I could be wrong.

The following is the function where I change the position of the rigidbody.

private GameObject ConvertConvexPolygon2DToShard(Vector2[] polygon, Transform relativeTo){
//relativeTo is the glass piece being shattered, which is used here to move the newly created polygon to the correct place
if(emptyShardsIn.childCount == 0){
CreateEmptyShards();
}
GameObject shatterPiece = emptyShardsIn.transform.GetChild(0).gameObject; //Get a pooled object
shatterPiece.SetActive(true);
GlassInfo glassInfo = shatterPiece.transform.GetComponent<GlassInfo>();
Rigidbody rigidbody = glassInfo.m_rigidbody; //So that I wouldn't have to do GetComponent<T>() everywhere
rigidbody.rotation = relativeTo.rotation;
MeshFilter meshFilter = glassInfo.meshFilter;
MeshRenderer meshRenderer = glassInfo.meshRenderer;
shatterPiece.transform.parent = glassPieces;
meshRenderer.material = brokenGlassMaterial;
Mesh newMesh = new Mesh();
Vector3[] vertices = new Vector3[polygon.Length];
int[] triangles = new int[(vertices.Length-2)*3];
Vector2 addedPoints = new Vector2(0,0);
for(int i = 0; i < polygon.Length; i++){
Vector2 point = polygon[i];
addedPoints += point;
}
Vector2 pointsMedianCenter = addedPoints/polygon.Length;
rigidbody.position = relativeTo.position + relativeTo.right * pointsMedianCenter.x + relativeTo.up * pointsMedianCenter.y;
//Debug.Log(rigidbody.position); //Adding BOTH of these makes the issue stop
//Debug.Log(relativeTo.position); //When printing these out by themselves though, everything seems alright
for(int i = 0; i < polygon.Length; i++){
Vector2 point = polygon[i];
vertices[i] = Vector3.right*(point.x-pointsMedianCenter.x) + Vector3.up*(point.y-pointsMedianCenter.y); //Move the vertices to counter the rigidbody moving
}
//The following is most likely unimportant
for(int i = 2; i < vertices.Length; i++){ //Fill the polygon
int triangleStart = (i-2)*3;
triangles[triangleStart] = 0;
triangles[triangleStart+1] = i-1;
triangles[triangleStart+2] = i;
}
newMesh.vertices = vertices;
newMesh.triangles = triangles;
meshFilter.mesh = newMesh;
return shatterPiece;
}

Note that I have filtered the code a bit to get rid of completely unimportant lines such as changing the name of the object

In the code, when logging the two positions by themselves so that the problem still appears, everything seems to be fine which, again, leads me to believe towards this being a timing problem.

I have attempted to get help for this problem multiple times (in the discord server), but without success.
Also, I apologize, as this is the first time I use this forum and I might have gotten something wrong, or forgotten to include information that I should have included.

This could totally be an oversight by me, but I haven’t been able to fix this for over a week now so I have come here for help.

Linux - Unity Version 2022.3.7f1

According to the documentation:

“If you want to continuously move a rigidbody use MovePosition instead, which takes interpolation into account.”

So if these shards are moving, which I think you mention is the problem, try:
rigidbody.MovePosition(position);
And see if that helps. :slight_smile:

Doesn‘t get the position changed to where it should be: what should it be and what is actually happening? What exactly is the incorrect position? Does it correlate with some other object?

When do you call this method? From Update, FixedUpdate, or some other Unity event? If you suspect a timing issue you could defer the code by starting a coroutine that yields null (or WaitForFixedUpdate) once and then calls the method.

Personally I suspect it could be an odd scenario where it matters whether this code runs in Update vs FixedUpdate since you extrapolate the position. In such a case it‘s advisable to modify rigidbody properties only in FixedUpdate because during Update the body‘s position is being inter/extrapolated.

This would fall in line with the suspicion of this issue being timing related.

No, that’s not quite what I want, I need to teleport them to the place the glass broke at first, not move them there continuously, but rigidbody.position = …; seems to not always actually set the position.

This code is being ran when the player shoots at the glass, which is checked for in Update.

What should be happening is that once the player shoots at the glass, the broken pieces are generated and then positioned to the glass with a little offset, but what is happening is that the glass isn’t being moved at all, it just stays at 0,0,0 where the “emptyShardsIn” objects were created to. I am yet to find any correlation with other objects or the behaviour of the player, other than maybe the timing, but I haven’t been able to confirm that yet.

I suppose I can try to store the changes that need to be done in FixedUpdated in a list and let them be done the next time FixedUpdate is called.

If the FixedUpdate thing stated above doesn’t help then I’ll try this, but I am a little unsure if this would change anything if this is timing related and also I definitely couldn’t keep it like that as the delay would probably be noticable.

That’s not going to be true; setting the body position will work just fine whenever you do it. You can verify this by setting it and read it immediately after. If that doesn’t read back what you set then you are correct and it should be reported as a bug.

What I expect is though that you’re saying “not always actually set the position” to mean the Transform position or some code depending on the Transform position. Setting the body position will only do that. The Transforms are only updated when then simulation is run as is all other physics related data.

If you’re saying that if you read the body position by printing it out and it’s all then working, that sounds like auto-sync-transforms is on which will, if you read a property that has a transform change, will update it there and then. You should avoid this and NOT have that property on (it’s off by default). You’re also doing Transform work by reparenting which makes things very confusing; that stuff doesn’t affect the physics stuff immediately.

The main thing to always know is that the Transform pose != Rigidbody pose. They are completely separate and during normal operation, the Rigidbody will write its pose to the Transform pose when the simulation is run which, by default, is during the FixedUpdate.

Mixing Transform reparenting, setting body rotation/position, doing calculations before that has updated etc is asking for bugs/confusion. You need to use one pose as your reference, don’t change and mix them up.

I’ve tried to look over your code but the poor formatting is giving me a headache and it’s not clear what is going on TBH.

Oh, and I have also noticed that if I change the transforms and the rigidbodies position then it works. This is most likely very inefficient and I’d much rather only have to move one of them, but moving only the transform also doesn’t work and I had moved to changing the rigidbodies position due to that a while back. This feels pretty interesting to me.

Yeah, I don’t really know why the code looks like that.
I am slightly confused of the response, but anyways, I am not changing the transform position. And also I don’t have auto-sync-transforms on, I think, at least I haven’t intentionally enabled it.
I had changing the unused and used shards being parented to just storing them in separate arrays or smth on my to-do list, but I didn’t know that changing the parent could affect the current situation.
I’ll try and see if it will fix the issue, if not, I’ll continue trying the things others have suggested.

EDIT:
Yeah, sadly, but as expected, removing the parenting thing didn’t change anything.

Yep, changing the position and rotation in FixedUpdate seems to have fixed the problem.

Where do we find documentation on this? How do we correctly process this stuff - I don’t mind doing it, I just need to know what the requirements (of Unity Physics) are.

So far I’ve been trial-and-error figuring out all the different parts of this that are undocumented and reverse-engineering what the missing docs could/should say. Things like “RigidBody.position having no effect” are relatively easy to demonstrate - a physics scene only slightly bigger than trivial will do it - and yes of course it’s because of something else (internal to Unity) but without docs how are we supposed to know what/where?

e.g. I have a simple repro case where:

  1. Set to kinematic
  2. Set rigidbody.position - read value back - its been set
  3. Set back to non-kinematic
  4. Pause runtime immediately (Debug.Break)
  5. In editor: after pausing, check the value of RB.position (its still correct)
  6. Advance one frame, check … and RB.position has been reset to 99/100 * Transform position + 1/100 * RB.position.

There’s no apparent reason for that reset.

That’s not a realistic constraint for a game - we can’t just discard the entire Transform API and all code ever written that uses those APIs :(. So … we need docs on how to make Unity Physics actually work correctly with ‘the rest of Unity’. So far I cannot find that documentation (maybe I’m reading the wrong parts, but RigidBody doesn’t describe it, nor does Collider, nor do the RigidBody.* API docs)

e.g. this code, on project with ‘auto sync transforms’ disabled, when called in FixedUpdate:

(deleted - I originally used the code without kinematic, but the code I pasted I’d enabled kinematic in a desperate attempt to keep things simpler - I forgot the GOTCHA that you must NOT use .position when isKinematic is true)

does nobody know about this?

Unity - Scripting API: Rigidbody.MovePosition (unity3d.com)

the proper way to move a rigidbody

Yeah, the point of the thread is that RB’s position methods usually work - but not always.

In my case I believe I have it narrowed down to:

  1. RigidBody root object
  2. With one or more RigidBody child objects
  3. And any of the child RB objects ALSO move…

(doesn’t matter if called in FixedUpdate or elsewhere)

has the effect of:
3. Breaks RB.position + RB.MovePosition if used while isKinematic = false
4. Breaks transform.position when used while isKinematic = true

… but in different ways.

If I only have a single RB then I can safely move it in kinematic via .transform, or I can move outside kinematic via .position.

It’s only when there are multiple RBs present that it fails - but it fails badly.

For anyone still having this issue like I was,

You can just call Physics.SyncTransforms() right after modifying the transform.position as suggested here:

(Assuming you’re not using this in something like Update that runs frequently)

Just ran into the same issue and can confirm the observation from here that the issue occurs only with nested rigidbodies. In my case, the rigidbody ends up having a position that is somewhere between its previous and the newly set position.

Calling Physics.SyncTransforms() did not resolve the issue for me.

What worked was setting transform.position on the rigidbody instead of rigidbody.position. That is not recommended practice but I don’t exactly know the consequences beyond “strange behavior because of the physics simulation”.

I have not tried delaying setting the position to FixedUpdate yet. If that should indeed be necessary, the docs for rigidbody.position definitely need to point that out. And I strongly agree with this post about the need for proper documentation about this. I strongly hope that delaying the use of rigidbody.position to FixedUpdate is not the solution because that would make using it much more complicated.

This thread has been marked as resolved. I don’t think it is.

The consequences are that the Rigidbody.position and Transform.position are two completely independent things and setting one doesn’t update the other. There’s nothing magical or complex about it.

Setting the Rigidbody.position happens instantly, same with the Transform.position. Verify this by reading it back immediately afterwards. Changing one Rigidbody.position doesn’t automagically change any other Rigidbody.position.

When the simulation runs, it first checks if any Transforms were changed (hopefully not) but if so, it has to write the Transform.position (and rotation) to the Rigidbody.

As always, when the simulation is finished, write-back occurs i.e. the Rigidbody write their poses to the Transforms which is how it’s supposed to work.

All this is a consequence of running the simulation out-of-sync with the render frame-rate. One thing runs without the other. If you were to run physics per-frame (which you can do) then this wouldn’t be the case.

This is why the rule always is, use the Rigidbody API.

@MelvMay thanks, much appreciated!

Regarding the topic of this thread, your explanation suggests that by setting transform.position instead of rigidbody.position and consequently triggering the physics simulation to update rigidbody.position internally, I get lucky in the sense that the update happens at the right time in the sequence for things to work out, i.e. for rigidbody.position to end up with the intended value.

I would very much like to stick to the rule of using the Rigidbody API and leave it up to the simulation to do the syncing. But as reported above, this does seem to lead to unexpected results under certain circumstances.

To hopefully get to the bottom of this and find a satisfying solution, I have set up this repo with a scene containing the three cases discussed:

  • case 1: without nested rigidbodies
  • case 2: with nested rigidbodies, using Rigidbody.position
  • case 3: with nested rigidbodies, using Transform.position

The video shows that case 2 does not get the rigidbody to the intended position.

As I said earlier, when you change the Rigidbody.position, it only changes that. It doesn’t scan the hierarchy and look for other Dynamic Rigidbody and update them. What it does is what it says on the tin.

In your case, you’ve got another Rigidbody as a child but the issue is that you’ve got them connected via a joint. When you move one of the Rigidbody, you’re expecting the joint to “just sort it out” but the joint can move both Rigidbody so that’s what it does.

The other Rigidbody is still where it is and when the simulation runs, the joint moves them back to some mid-point and don’t forget, joints have cached solver state which you’ve upset a little so it’s the joint doing this. A quick way to see this is if you set the mass-scale of your joint to near zero so it doesn’t drag it back.

When you change the Transform, the whole Transform hierarchy changes but no Rigidbody poses change until the transforms are synced which happens prior to the simulation running (or if you explicitly call it). When this happens they are both teleported and the joint then works as this joint just needs them to be relative so its cached state is likely happy then.

In the end, you don’t get physical motion when you modify the Transform nor is it physical motion when you change the Rigidbody pose directly. The problem here is that it’s always stated to not change the Transform because it breaks physical motion but that’s exactly what you want here in your test!

If you’re directly changing physics poses then you should be using a Kinematic body with MovePosition and MoveRotation etc.

This is also a classic case where you’re assuming the same problem as the OP which isn’t the case. You are changing the Rigidbody.position but you have a joint connected to another Rigidbody which you’re not changing. This is just a bad scenario you’ve set-up. In reality, you wouldn’t have a fixed-joint like this, it’d just be a collider as a child.

Thanks again, @MelvMay .

My scenario isn’t bad, thank you very much. It was just an attempt to get the same kind of behavior as in the more complex one I am working on. One reason to have a fixed joint like that is to have a compound object where a part can break off if sufficient force is applied.

Having said that, I do get your point about the influence of the joint and I understand how this can produce the observed behavior. I had not thought about that aspect and I thank you for pointing it out! It’s also clear now how this problem is different from the OP.

There are a number of points in your post that I’ll need to explore further - thanks for the pointers!

Ah okay, that’s fair enough. By bad I meant there’s a much better alternative than using Dynamic bodies in a hierarchy with a fixed-joint given what I knew of your test. :slight_smile:

Yes, joints are the most “sensitive” things in physics because they typically have a whole bunch of cached stated and often it doesn’t like suddenly finding itself way outside of constraints. This can lead to joints “exploding” or just giving you undefined or unexpected behaviour.

I guess the main take away from what I said was that we often state don’t change the Transform for many specific reasons but that’s not to say there’s no situations where you should/can. Knowing how things work is the most important part and that always starts with knowing that Transform pose and Rigidbody pose are not the same state (especially when interpolating) and joints don’t like you messing with pose directly, at least not with a large pose delta. The final one is that Dynamic bodies in a hierarchy is kind of “awkward”. The physics has no knowledge of this hierarchy with Dynamic bodies, only Kinematic ones. :slight_smile:

Just for the record here, I work on 2D physics not 3D physics although the two are integrated in a similar way.