Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Locking movement to a path?

Discussion in 'Editor & General Support' started by Drewpie, May 14, 2020.

  1. Drewpie

    Drewpie

    Joined:
    May 12, 2020
    Posts:
    2
    Hi all,

    I'm afraid I'm extremely new to Unity and I'm having all sorts of issues trying to lock a camera/player to a path.

    Full context: I'm trying to model an experience that allows a user to move up and down a corridor by using simple forward and back keys. At the same time, I'd like to all the user to click and drag the camera around to look at various things.

    I've got a drag-able camera at the moment utilising the simplecameracontroller script included in the High Definition RP sample scene (which I've stripped of the forward/back/left/right controls)

    I've tried a camera on a dolly, splines from Surge, constrained movement and I've spent the best part of a day trying to google the answer (and hopefully learn in the process)

    I'm out of ideas. I just cannot figure out how to code a simple function that allows a camera to move along a pre-determined path when the user presses forward or back (up/w, down/s)

    Please could I ask for some guidance?

    Thanks very much,

    Drewpie
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Is this just a straight corridor?

    What if you had two gameobjects, one on either end of the corridor? Then you can map W and S to moving towards those two points:

    Code (CSharp):
    1. public Transform FrontOfCorridor;
    2. public Transform BackOfCorridor;
    3. public float MoveSpeed;
    4.  
    5. void Start() {
    6.   transform.position = BackOfCorridor.position;
    7. }
    8.  
    9. void Update() {
    10.   if (Input.GetKey(KeyCode.W)) {
    11.     transform.position = Vector3.MoveTowards(transform.position, BackOfCorrido.positionr, MoveSpeed * Time.deltaTime);
    12.   }
    13.   if (Input.GetKey(KeyCode.S)) {
    14.     transform.position = Vector3.MoveTowards(transform.position, FrontOfCorridor.position, MoveSpeed * Time.deltaTime);
    15.   }
    16. }
     
    Drewpie likes this.
  3. Drewpie

    Drewpie

    Joined:
    May 12, 2020
    Posts:
    2
    I could cry - that's exactly what I was looking for!!! Thank you so much!!
     
    PraetorBlue likes this.