- Home /
my MainChara shakes when the Mathf.Clamp stops it from going off screen
I want to clamp the player from getting out of the screen in any resolution. It is working but when it stops it, my ship (side scroller) starts shaking as if it was actually push back. The last time I used the clamp it didn't shake... this is the code I used:
function Start () {
}
function Update () { var dist = (transform.position.z - Camera.main.transform.position.z); var leftLimitation = Camera.main.ViewportToWorldPoint(Vector3(1,0,dist)).x; var rightLimitation = Camera.main.ViewportToWorldPoint(Vector3(0,1,dist)).x; var upLimitation = Camera.main.ViewportToWorldPoint(Vector3(0,1,dist)).y; var downLimitation = Camera.main.ViewportToWorldPoint(Vector3(1,0,dist)).y;
transform.position.x = Mathf.Clamp(transform.position.x, rightLimitation + 2, leftLimitation - 2); transform.position.y = Mathf.Clamp(transform.position.y, downLimitation +1, upLimitation - 1);
}
Is there someone here who know how to fix this?
Is there a reason that you don't set your limitations on movement when the class is constructed? I'm wondering if this constant redefinition of 'var dist' and the limitations isn't causing this jitter.
Answer by Zoraph · Dec 11, 2012 at 06:16 PM
I am not sure what you mean by that, I am not that good with classes yet, but either way, the problem has been solved and I don't know why since I didn't do anything.... I woke up this morning and it was working fine and I didn't even close Unity.
but just in case, is there something wrong with the way I did it or could it causes problems if it is called in a function Update because I tried putting the var outside first and it gave me an error message and it didn't work. It works when it is in the update but it was jittering a lot.... but not anymore for some reason lol ;)