Search Unity

Lining up a box collider with an orthographic camera

Discussion in 'Scripting' started by Mr_Admirals, Feb 8, 2019.

  1. Mr_Admirals

    Mr_Admirals

    Joined:
    May 13, 2017
    Posts:
    86
    For a visual effect I'm working on, I need an orthographic camera triggered by a box collider. To do that, I would like the box collider to be perfectly lined up with the Camera's viewing box, so that any object that enters the camera's view will turn the camera on. When everything is oriented at a rotation of (0, 0, 0), my code works great. But modifying the X and Z components of a rotation causes the box collider to be slightly misaligned.

    For the visual effect, the camera is always looking at a planar mesh, so I can use the bounds of the plane to get the X and Z bounds of collider. The Y value is what I'm struggling with. Also worth mentioning is that the box colliders are being set up programatically to get them as lined up as possible.

    Here's the relevant code:

    Code (CSharp):
    1.     private void Start()
    2.     {
    3.         SRTP = transform.GetChild(0).GetComponent<SnowRenderTexturePipeline>();
    4.  
    5.         Bounds meshLocalBounds = transform.parent.GetComponent<MeshFilter>().sharedMesh.bounds;
    6.         Bounds meshWorldBounds = transform.parent.GetComponent<MeshRenderer>().bounds;
    7.         float colliderHeight = SRTP.groundCam.farClipPlane;
    8.         boxCollider = GetComponent<BoxCollider>();
    9.         boxCollider.center = new Vector3(0, meshWorldBounds.center.y - transform.parent.position.y + SRTP.displacement / 2f, 0);
    10.         boxCollider.size = new Vector3(meshLocalBounds.extents.x * 2f, colliderHeight, meshLocalBounds.extents.z * 2f);
    11.  
    12.         SRTP.SetActive(true);
    13.  
    14.         objectCam = transform.GetChild(0).GetComponent<Camera>();
    15.         objectCam.Render();
    16.         groundCam = transform.GetChild(1).GetComponent<Camera>();
    17.         groundCam.Render();
    18.     }
    Here's some pictures illustrating the problem:

    Perfectly aligned with no rotation:
    upload_2019-2-7_23-16-2.png

    Misaligned with rotation:
    upload_2019-2-7_23-17-49.png
     
    Last edited: Feb 8, 2019
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Are you parenting the object with the box collider to the camera? Or you can parent both the camera and the box collider to a common object and only rotate that object.
     
  3. Mr_Admirals

    Mr_Admirals

    Joined:
    May 13, 2017
    Posts:
    86
    Thanks for the reply. I actually ended up figuring it out. It was a formula I thought I'd tried before but apparently didn't.
     
    Kurt-Dekker likes this.