Search code examples
c#unity-game-enginegame-physics

Unity - How to tell whether translate function will take object outside certain bounds?


Alright Im using a joystick to move my camera in Unity like this:

moveVector = (transform.right * joystick.Horizontal + transform.forward * joystick.Vertical);

transform.Translate(moveVector * speed * Time.deltaTime, Space.World);

However I need to limit where my camera can move to within the bounds of a boxcollider (the room, stored in a variable). Ive tried this but this always returns true even when the camera moves out of range:

print(GameObject.FindObjectOfType<PlayerController>().room.bounds.Contains(moveVector));

How can I detect whether the translation would move the camera out of bounds, and if this is true, not do the translation with the move vector?


Solution

  • The problem is that you are using the displacement of the camera ('moveVector') to determine whether the camera is in the bounding box. Instead you should use the position of the camera,

    gameObject.transform.Position 
    

    or the future position of the camera,

    gameObject.transform.position + moveVector
    

    to determine whether it is in the bounding box or not. Thus, modify your code as follows:

    GameObject.FindObjectOfType<PlayerController>().room.bounds.Contains(camera.transform.position + moveVector)
    

    Make sure your 'room' variable is of type Collider in the 'PlayerController' script,

     var room = GetComponent<Collider>();