Search Unity

Beginner Noob Question

Discussion in '2D' started by ThePaul, Mar 20, 2017.

  1. ThePaul

    ThePaul

    Joined:
    Jan 15, 2017
    Posts:
    13
    I simply want the camera to stay in the middle between two game objects, (its like a co-op game), everything ive tried hasnt worked. can anyone help please? its 2d btw!
     
  2. ShadyProductions

    ShadyProductions

    Joined:
    Jul 21, 2014
    Posts:
    18
    Group the 2 gameobjects in an empty gameobject
    put the camera inside of the group and move it exactly in place where you want it to be.
    Now when the group moves the camera will move too and will stay wherever you put it.
     
  3. Fabian-Haquin

    Fabian-Haquin

    Joined:
    Dec 3, 2012
    Posts:
    231
    Get the position between the two GameObjects:

    Code (CSharp):
    1. Vector3 posBetween = Vector3.Lerp(obj1.transform.position, obj2.transform.position, 0.5f);
    Then you can apply an offset to this position (or the camera will be really between the two in the ground).

    Code (CSharp):
    1. posBetween += cameraOffset;
    If you want to apply a rough delay in a sec you can do this:
    Code (CSharp):
    1. float smoothSpeed  = 3; // tweak this
    2. cam.transform.position = Vector3.Lerp(cam.transform.position, posBetween, Time.deltaTime * smoothSpeed);
    It's doesn't change much for 2D.
     
    JoshGreen likes this.
  4. JoshGreen

    JoshGreen

    Joined:
    Mar 16, 2017
    Posts:
    28
    Fabian-Haquin I really like your way of getting the midpoint with a 50% lerp :)
     
  5. Fabian-Haquin

    Fabian-Haquin

    Joined:
    Dec 3, 2012
    Posts:
    231
    Well you can also take the direction from obj1 to obj2 then takes the distance and do obj1.position + dir * dist * 0.5f but that's basically what lerp do.
     
  6. JoshGreen

    JoshGreen

    Joined:
    Mar 16, 2017
    Posts:
    28
    That's how I was going to suggest to do it, I know how lerp works but haven't ever thought about using a lerp to do things like this so thumbs up.
     
  7. ThePaul

    ThePaul

    Joined:
    Jan 15, 2017
    Posts:
    13
    so it looks good but what do you mean apply an offset? how do i do that
     
  8. ThePaul

    ThePaul

    Joined:
    Jan 15, 2017
    Posts:
    13
    nvm i got it :)
     
    Fabian-Haquin likes this.