Keeping to the Z axis in FixedUpdate using C#

I’m befuddled (again! surprise!).

I have a spaceship I want to constrain to the Z axis just like in the 2d gameplay demo (except this isn’t a platformer). Anyway, here’s what I’m doing, abridged for your clarity/convenience.

private Vector3 _position;

public void Start()
{
    _position.x = transform.position.x;
}

public void FixedUpdate()
{
    _position.x = transform.position.x;
    _position.y = 0;
    _position.z = 0;

    transform.position = _position;
}

When the player collides, though, it goes spinning off in all directions as if the y/z were not being zeroed each update. So, I’m doing something wrong. But I can’t figure out what it is.

Help?! :sweat_smile:

When a gameobject is under control of the physics engine, you can’t just update the object by manipulating its’ Transform component: the two don’t mix as the updates computed by the physics engine take priority and/or have the final say as to where/how the object winds-up.

The proper way to manipulate an gameobject under physics control is via the Rigidbodys’ MovePosition MoveRotation functions.

Also, look into Configurable Joints, as this type of joint allows you to lock the movement/rotation of an object along/about a specific axis.

Ahh, I see. Since the 2d platformer tutorial controller isn’t using RigidBody, it works. That makes sense.

Thanks again, David! :slight_smile: