Search Unity

Camera Move

Discussion in 'Scripting' started by Kevin9595, Apr 26, 2015.

  1. Kevin9595

    Kevin9595

    Joined:
    Nov 5, 2014
    Posts:
    8
    Hi Unity Community!!!

    I'm very new at Unity (1 month only) and I want in my "I'm-learning" 2d game a camera (orthographic) to constantly move right when my player's in the trigger only. If the player gets out the trigger, the camera will stop moving and will move on to the cameraFollow Script.

    I can already make the camera move by itself, but I want it to stop when the player's out the trigger.

    Camera

    public class cameraMovement : MonoBehaviour
    {
    public static int movespeed =1;
    public Vector3 cameraDirection =Vector3.right;
    public Start () {
    }
    public void Update() {
    transform.Translate(cameraDirection * movespeed *Time.deltaTime);
    }
    }

    Thank you so much!
     
  2. Kevin9595

    Kevin9595

    Joined:
    Nov 5, 2014
    Posts:
    8
    If anyone can take a shot at this, that'll be great!
     
  3. Aidy

    Aidy

    Joined:
    Oct 15, 2014
    Posts:
    19
    If you want a trigger then you should learn about OnTriggerEnter and OnTriggerExit. The way I'd do it (which is probably quite unoptimised and dirty) is I'd create another function in the camera script which controls the movement of it (which is what you have in update, if it's in Update it'll do it every single frame unless you have something telling it to stop if certain conditions are met). Then I'd have an if statement with a bool saying that if the camera trigger is true - if it's been activated - then use that code in update. I hope I've explained this right.

    In the player's movement script you'd need to do the OnTriggerEnter/Exit code which is fairly straightforward, as well as the getting the component of the camera so you can access its variables. The variable you'd want is the bool, simply set it to true when the player enters the trigger, then false once he exits it.

    That should work. I can't promise it will, I would write it for you so you get what I mean, but it really is quite simple and I think you'd learn more if you wrote it yourself. I'm also not at home so I can't anyway. I hope this helps c:

    Ooh, this is somewhat related, another tip for camera movement in general is to execute it in LateUpdate. You don't need it in this case because the camera isn't tracking anything, but for a camera that does then LateUpdate would only be logical. It's something to bare in mind for optimisation and to save you frustration of cameras misbehaving c:
     
    Kevin9595 likes this.