- Home /
Clamping Issue
I have limited the y movement by clamping the values. But still the object moves beyond the clamped values. Not quiet sure what is the reason behind the problem.
Any help would be appreciated.
Edit: If I replace this rigidbody2D.velocity = movement*Speed;
with this player.transform.Translate(movement*Speed*Time.deltaTime);
it works fine.. It is clamping as intended. But the movement is not smooth as rigidbody2D.velocity. I need to translate the object by rigidbody2D.velocity. I need to know what is the issue! It is really frustrating for weeks now!
Thanks.
switch(phase)
{
case TouchPhase.Began:
touchStartPos = Camera.main.ScreenToWorldPoint(touch.position);
break;
case TouchPhase.Moved:
touchEndPos = Camera.main.ScreenToWorldPoint(touch.position);
differencePos = touchEndPos.y - touchStartPos.y;
movement = new Vector2(0,differencePos);
rigidbody2D.velocity = movement*Speed;
Vector3 Pos = transform.position;
Pos.y = Mathf.Clamp(Pos.y,maxY,minY);
clampPos.y = Pos.y - transform.position.y;
transform.Translate(clampPos);
break;
}
Answer by tanoshimi · Feb 02, 2015 at 06:56 AM
The only thing you're clamping is Pos.y
. Did you mean to clamp clampPos.y
, which is the y component of the vector you're actually translating by?
Thanks for your quick reply. Am translating by the rigidbody2D.velocity. I need to clamp the translation y value.
I have tried clamping both pos.y and clampPos.y, Both is not clamping the movement.. The object keep moving in y axis... It need to be clamped maxY,$$anonymous$$Y.
Translate moves your transform in a direction with some amount of speed, clamping the values as you have done simply stops the object moving more than a certain speed not moving more than a certain position.
rigidbody2D.velocity = movement*Speed;
Vector3 Pos = transform.position;
Pos.y = $$anonymous$$athf.Clamp(Pos.y,maxY,$$anonymous$$Y);
transform.position = Pos;
Haven't you just got your $$anonymous$$ and max the wrong way round in the clamp call?
Your answer
![](https://koobas.hobune.stream/wayback/20220613182209im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to Touch Drag 3D Objects 2 Answers
Mobile game Player follow finger input problem (C#) 2 Answers
Swipe to move object: object sometimes flying off screen even though value is clamped 1 Answer
working on an endless runner. Need help with clamping. 1 Answer
How can i drag objects smoothly with touch? Please help me with this code! 1 Answer