Search code examples
unity-game-enginegame-physics

Moving a physics button with fixed axis after rotation in Unity


I'm trying to make a physics based button as shown below.

Button rigidbody

The red cube should travel down on the Y axis when force is applied and hit the trigger (the light grey box).

I have achieved this by making the red cube a rigidbody and freezing rotation and position (except on Y axis). The red cube is attached to the trigger via a sprint joint.

This works pretty well, until I try to rotate the whole container for the button, and then the button depresses on the world Y axis (red arrow below) instead of it's local Y axis (green arrow below).

movement after rotation

How can I fix this? Thanks!


Solution

  • Figured it out, this code will restrict movement to the local y axis only and remove the freeze position flags on the rigidbody component

    void Update()
    {
        transform.localPosition = new Vector3(0, transform.localPosition.y, 0);
    }