My player shakes when Mathf.Clamp stops it from going off screen.


Is there a way to prevent this from happening? If I hold “up” and my player reaches the top of the screen, Mathf.Clamp prevents it from going any further, but if I keep hold “up”, my player shakes like he’s trying to break through or something. It’s bizarre- here’s the code:

void FixedUpdate()

		transform.position = new Vector3(transform.position.x, 
			Mathf.Clamp(transform.position.y, -3.479f, 7.25f), 

		// calculate the speed multiplier here from directionY
		float speedMultiplier = GetSpeedMultiplier(directionY);

		// use the speedMultiplier in place of directionY
		rb.velocity = new Vector2(rb.velocity.x, speedMultiplier * moveSpeed);

The first detail to note is that you’re doing this in FixedUpdate(). Your character’s position will visibly appear to change every rendering frame (Update()), while your position will be clamped asynchronously to the rendering.

Furthermore, this is able to occur in the first place because hitting that “ceiling” doesn’t actually modify your velocity. You’re still trying to move upwards (velocity), but just teleporting your character downward over and over (position). If you clamp the position during Update(), then this behavior shouldn’t visibly occur.