- Home /
Position Limit
I need to limit the position of an object, but depending on it's current x value in editor/inspector.
Let's say, i've got an object, and i moved it by it's x position for positive 2. Now it's x cor is 2 in inspector. And what i want to do is to limit that coordinate so it can move up to 4, and min would be 0. So it doesen't move more than that, but i want to do this depending on it's current position in inspector. So if it was example 5, it's max would be 7 and min 3, so it moves just by 2 on it's x... Can't explain better, anyone can help ?
btw. if you've got a code, C# would be nice
Answer by michael96schmidt · Jan 18, 2015 at 05:44 AM
I'm a little bit confused by your phrasing but mathf.clamp() would probably be helpful.
Actually i've solved my problem, i just tought about it, and figured it out, here, i'll post an answer.
Answer by RickyX · Jan 18, 2015 at 06:56 AM
Well i tought about my problem, and i got an idea and i made a code for this myself, works perfectly fine, i even made it more advanced, if anyone needs it, here it is:
using UnityEngine;
using System.Collections;
public class LedgeHandOffsetScript : MonoBehaviour
{
public Transform Target;
public Transform OffsetMin;
public Transform OffsetMax;
public float minMove;
public float maxMove;
public float RegPoseX;
public float RegPoseY;
public float RegPoseZ;
public bool FreeLimitsToggle;
public string MoveCor;
void Start ()
{
Vector3 RegPose = transform.position;
RegPoseX = RegPose.x;
RegPoseY = RegPose.y;
RegPoseZ = RegPose.z;
}
void FixedUpdate ()
{
Vector3 pos = transform.position;
if(MoveCor == "x")
{
pos.z = RegPoseZ;
pos.y = RegPoseY;
pos.x = Target.position.x;
if(FreeLimitsToggle == true)
{
if(pos.x > minMove)
{
pos.x = minMove;
}
if(pos.x > maxMove)
{
pos.x = maxMove;
}
}
else
{
if(pos.x > OffsetMax.position.x)
{
pos.x = OffsetMax.position.x;
}
if(pos.x < OffsetMin.position.x)
{
pos.x = OffsetMin.position.x;
}
}
}
else if(MoveCor == "z")
{
pos.z = Target.position.z;
pos.y = RegPoseY;
pos.x = RegPoseX;
if(FreeLimitsToggle == true)
{
if(pos.z > minMove)
{
pos.z = minMove;
}
if(pos.z > maxMove)
{
pos.z = maxMove;
}
}
else
{
if(pos.z > OffsetMax.position.z)
{
pos.z = OffsetMax.position.z;
}
if(pos.z < OffsetMin.position.z)
{
pos.z = OffsetMin.position.z;
}
}
}
transform.position = pos;
}
}
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Resetting a position after reaching a certain point 2 Answers
C# Transform modification. 1 Answer
Making a race car positioning system 5 Answers