Search Unity

Switching cameras when player collides with gameobject

Discussion in 'Getting Started' started by Praht, Jan 7, 2023.

  1. Praht

    Praht

    Joined:
    Jan 7, 2023
    Posts:
    1
    I feel rather underqualified to be posting on this forum but I digress,

    I'm making a simple 3 level platformer as my first project and I need the game to switch to another camera once it collides with a invisible gameobject

    I've tried to figure this out on my own and I've been unsuccessful.
    How could I solve this? any help/advice is greatly appreciated
     
  2. ZingZangGames

    ZingZangGames

    Joined:
    Dec 11, 2020
    Posts:
    73
    On the invisible object, you'd need to add a script, where you check for collision and check if the colliding object is actually your player. If that's true, you'd switch the cameras by just disabling the currently used one and enabling the one you want to switch to.

    The script could look like this:
    Code (CSharp):
    1. public Camera mainPlayerCam; // Cam, that your player actively uses
    2. public Camera otherCam; // Camera to which the player is switched to
    3.  
    4. void OnCollisionEnter(Collision collision)
    5.     {
    6.         // Something collided with this object (the invisible object). Now we need to know if that was the player
    7.         if (collision.collider.gameObject.CompareTag("Player"))
    8.         {
    9.                         // Switch cameras
    10.                         mainPlayerCam.enabled = false;
    11.                         otherCam.enabled = true;
    12.         }
    13.     }
    This assumes that the collider of your player has the tag "Player" assigned to it (you can change that at the top of your player-collider's inspector). Hope this helps!

    Some reminders:
    - If this doesn't work, try adding a Rigidbody component on your invisible object (where the scribt above should also be located) and switch its "IsKinematic" property on.
    - For future posts, also try to provide more precise info, like whether it's a 2D or a 3D game and what you mean by "it collides..." (I assume the player :))
     
    Last edited: Jan 11, 2023
  3. Inxentas

    Inxentas

    Joined:
    Jan 15, 2020
    Posts:
    278
    The mechanic described sounds like you want this invisible object to be a Trigger.

    So instead of using the OnCollision method, you might opt to use the OnTriggerMethod instead and setting the isTrigger value if the Collider to true. That way the object acts more like a zone you walk into, not blocking the player. I would advise you to play around with various Colliders (Box, Sphere) and the Rigidbody components and see what every option in the Editor does by working through the documentation for a spell.

    Humble beginnings are no reason not to post on the forums. I would imagine that someone that just starts out would have questions. That is what forums are for ;)
     
    ZingZangGames likes this.