Rigidbody local position constraints
I'm trying to make a rigidbody button which only moves forward and back, but it is rotated and the Rigidbody position constraints are in world space not local space. Is there any way to constrain the position in local space?
Answer by daniel4crew · Jan 27, 2017 at 04:04 PM
Hello @265lutab, maybe it's late to the party but I had the same trouble and I figured out a solution that worked correctly for me. Hope it will help you and other people.
using UnityEngine;
public class PositionLocalConstraints : MonoBehaviour
{
[Header("Freeze Local Position")]
[SerializeField]
bool x;
[SerializeField]
bool y;
[SerializeField]
bool z;
Vector3 localPosition0; //original local position
private void Start()
{
SetOriginalLocalPosition();
}
private void Update ()
{
float x, y, z;
if (this.x)
x = localPosition0.x;
else
x = transform.localPosition.x;
if (this.y)
y = localPosition0.y;
else
y = transform.localPosition.y;
if (this.z)
z = localPosition0.z;
else
z = transform.localPosition.z;
transform.localPosition = new Vector3(x, y, z);
}
public void SetOriginalLocalPosition()
{
localPosition0 = transform.localPosition;
}
}
Attach this script to the gameObject and select the axis to freeze.
Answer by pixeleif · Sep 03, 2020 at 12:06 PM
@daniel4crew Maybe late to his party, but just in time for mine! Thanks!
Your answer
Follow this Question
Related Questions
Falling Platform 1 Answer
localPosition not where expected 1 Answer
How to make a ball able to go anywhere on my "field"?? 0 Answers
Locking player's Y position while jumping and near a wall 0 Answers