- Home /
Question by
Infamous911 · Jul 29, 2011 at 02:25 AM ·
screenclampmathf.clampedge
Two Clamps on the Same axis
So I need to have an object confined to moving around only in the y axis between the top and bottom edges of the screen. This is what I have:
Vector3 viewPos = Camera.main.WorldToViewportPoint(transform.position);
viewPos.y = Mathf.Clamp01(viewPos.y + .128f);
viewPos.y = Mathf.Clamp01(viewPos.y - .128f);
transform.position = Camera.main.ViewportToWorldPoint(viewPos);
This doesn't work because for some reason, the clamp is only working at the top edge of the screen. At the bottom edge, it still allows half of the object to go through before stopping it. Why would this be?
Comment
Best Answer
Answer by aldonaletto · Jul 29, 2011 at 04:46 AM
Nothing seems wrong in your code, but I would prefer to use Mathf.Clamp:
Vector3 viewPos = Camera.main.WorldToViewportPoint(transform.position); viewPos.y = Mathf.Clamp(viewPos.y, 0.128f, 1 - 0.128f); transform.position = Camera.main.ViewportToWorldPoint(viewPos);If the object pivot is above its visual center, the bottom limit should be raised (you're clamping transform.position, which is set to the object pivot).
This works, not sure why my code wasn't working. Thanks!