Reputation: 15
My script is working almost perfectly, but I just need to clamp this float and I can't seem to figure out how.
A simplified version...
public HingeJoint doorHinge;
public float rotatedoor = 0.0f; // Limit this value, min 0 max 120
void Update () {
float h = Input.GetAxis("Mouse X");
rotatedoor = rotatedoor + h;
JointSpring doorSpring = Door.spring;
doorSpring.targetPosition = rotatedoor;
Door.spring = doorSpring;
}
I tried adding a min and max float value and then using
rotatedoor = Mathf.Clamp(rotatedoor, minRot, maxRot);
but no luck.
Any help is appreciated.
Upvotes: 1
Views: 320
Reputation: 125275
You got your answer about clamping it but you really don't need to do this.
It looks like you want to set the limit for HingeJoint
. This has built-in property to do so with the JointLimits
struct and that's what you should use.
Something like below:
public HingeJoint doorHinge;
public float rotatedoor = 0.0f; // Limit this value, min 0 max 120
void Update()
{
//Get the current the limit
JointLimits limits = doorHinge.limits;
//Set the limit to that copy
limits.min = 0;
limits.max = 120;
limits.bounciness = 0;
limits.bounceMinVelocity = 0;
//Apply the limit since it's a struct
doorHinge.limits = limits;
JointSpring doorSpring = doorHinge.spring;
doorSpring.targetPosition = rotatedoor;
doorHinge.spring = doorSpring;
}
Upvotes: 2
Reputation: 2970
There are a number of easy ways to do this, so I'll list the ones that I see below.
rotatedoor = Math.Max( 0f, Math.Min( 120f, rotatedoor ) );
Alternatively, you could use a ternary expression:
rotatedoor = (rotatedoor < 0f) ? 0f : (rotatedoor > 120f) ? 120f : value;
Or, you could use Unity3D's Mathf.clamp():
rotatedoor = Mathf.clamp( rotatedoor, 0.0f, 120f );
There are probably other ways of doing this as well. I would be interested in knowing if a more efficient method exists, since all of these techniques require operating in the update
logic, which is not the most efficient way to go about things per se. Hope this helps!
Upvotes: 1