RTS Camera wiggle approaching to clamped borders
I made borders for my RTS Camera using Mathf.Clamp but it started wiggling when the borders reached. I need smooth movements but Clamp doesnt work fine and my camera always cross the borders a little bit with floating position value. Any ideas ? This is my Code but I think , you guys needn't it: Clamp : transform.position = new Vector3( Mathf.Clamp(transform.position.x, cameraLimits.leftLimit, cameraLimits.rightLimit), transform.position.y, Mathf.Clamp(transform.position.z, cameraLimits.downLimit, cameraLimits.upLimit));
Translation Camera:
public Vector3 GetTranslation() { float moveX = 0.0f; float moveZ = 0.0f; float moveY = 0.0f;
float moveSpeed = cameraMoveSpeed * Time.deltaTime;
if (Input.mousePosition.x < mouseScrollLimits.leftLimit)
{
// Debug.Log("Left");
moveX = -moveSpeed;
}
else if (Input.mousePosition.x > Screen.width - mouseScrollLimits.rightLimit)
{
// Debug.Log("Right");
moveX = moveSpeed;
}
else if (Input.mousePosition.y > Screen.height - mouseScrollLimits.upLimit)
{
// Debug.Log("up");
moveZ = moveSpeed * Mathf.Cos(transform.rotation.eulerAngles.x * (Mathf.PI / 180));
moveY = moveSpeed * Mathf.Sin(transform.rotation.eulerAngles.x * (Mathf.PI / 180));
}
else if (Input.mousePosition.y < mouseScrollLimits.downLimit)
{
// Debug.Log("down");
moveZ =- moveSpeed * Mathf.Cos(transform.rotation.eulerAngles.x * (Mathf.PI / 180));
moveY =- moveSpeed * Mathf.Sin(transform.rotation.eulerAngles.x * (Mathf.PI / 180));
}
return new Vector3(moveX, moveY, moveZ);
}
Answer by JedBeryll · Jun 18, 2016 at 05:29 AM
Mathf.Clamp(transform.position.x ...
This implies you assign the position then reassign it with the clamped value. If that's the case, the solution is to not assign it twice.
Vector3 pos = GetTranslation();
transform.position = new Vector3( Mathf.Clamp(pos.x + transform.position.x, cameraLimits.leftLimit, cameraLimits.rightLimit), pos.y + transform.position.y, Mathf.Clamp(pos.z + transform.position.z, cameraLimits.downLimit, cameraLimits.upLimit));
Thx JedBeryll, nice idea about "not assign it twice". I found the issue. Translation was after clamping in the same frame. So I replace translation upper;