23 de mai. de 2017

How to limit the moviment of a GameObject into the Screen

This function limits the moviment of a GameObject to it´s Cam Screen.

private void CheckLimits(Vector3 posAtual)
{
    SpriteRenderer renderer = GetComponent<SpriteRenderer>();

    float newX = Mathf.Clamp(transform.position.x, 
        cam.ScreenToWorldPoint(new Vector3(0, 0, 0)).x + renderer.bounds.size.x/2, 
        cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, 0, 0)).x - renderer.bounds.size.x / 2);

    transform.position = new Vector3(newX, posAtual.y, posAtual.z);
}

Nenhum comentário: