Dancing Z value

hey all :slight_smile:

I’m making a side scroller currently and I have just written part of my character controller script. I’ll quickly give a rundown on how it all currently works:

Left and right movement uses the classic GetAxis method: (In FixedUpdate())

var translation = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
transform.Translate(translation, 0, 0);

and Jumping:

if (canJump)
{
  if (Input.GetKeyDown("space") || Input.GetKeyDown("w"))
    rigidbody.AddForce (Vector3.up * jumpForce);
}

So as you can see my character - currently just a capsule - has a rigidbody component. it also has a box collider. Freeze rotation is enabled.

Now I don’t want my character to be bouncy as it lands on the ground after jumping so I added a physic material with dynamic friction and static friction set to 1, and bouncyness set to 0.

The ground itself is a terrain which has the same physic material as the character.

Now the problem:

When I start the game, my character which I placed initially above the ground is affected by gravity and lands on the ground. When it lands on the ground its Z value which is initially 0 changes itself to a very small value like 0.00068. As I walk around in the level it gets larger no matter what direction I go. Eventually the value gets large enough and my character falls off the ground.

Why is this happening? How can I stop it? :frowning:

A curious observation: If I set dynamic and static friction to 0 the problem doesn’t happen. Z stays 0 the whole time, which is great, but since the friction is 0 my character would very slowly slide across the ground after moving and seem to never stop.

If you are using a rigidbody, you should not use transform.Translate, instead you should also use rigidbody.AddForce or rigidbody.MovePosition.
Did you have a look at the Lerpz tutorial? I think in the tutorial a Configurable Joint is used, which restricts the movement along the z axis. But as it is still not 100 percent stable, they have a script that sets the z value in every FixedUpdate or Update (not sure which one) to zero.

I had a quick look at the lerpz tutorial, it was quite long so I didnt go through it all. I looked at the configurable joint part just now and tried it however it didnt really work, I managed to get it to restrict rotations which pretty much does the same thing as Freeze Rotations, but locking the z axis didnt seem to work even after I changed the axis to the right one (should be y)

I just changed the transform.Translate to Rigidbody.MovePosition but the same problem still happens :frowning:

What about a script that sets z to zero every frame?

The configurable joint isn’t too hard to erm… configure. You just need to set the Z motion property to Locked and enable the Configured in World Space option. This will keep the character locked at the Z coordinate it started off with.