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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

'Grid' movement relative to Camera orbit

Discussion in 'Scripting' started by Panchos, Jun 6, 2020.

  1. Panchos

    Panchos

    Joined:
    Oct 31, 2012
    Posts:
    34
    I'm trying to move a cursor gameObject around a plane using the WASD keys. I suspect I'm closing in on the method, but it messes up at certain camera angles.

    Code (CSharp):
    1. var oldMoveTo = moveTo;
    2. Vector3 moveDir = new Vector3(0,0,0);
    3.  
    4. if (Input.GetAxis("Vertical") > 0f) { moveDir = Camera.main.transform.forward; }
    5. if (Input.GetAxis("Vertical") < 0f) { moveDir = -Camera.main.transform.forward; }
    6. if (Input.GetAxis("Horizontal") < 0f) { moveDir = -Camera.main.transform.right; }
    7. if (Input.GetAxis("Horizontal") > 0f) { moveDir = Camera.main.transform.right; }
    8.  
    9. // this method to 'snap' it to a grid
    10. if (moveDir.x < -0.3f) { moveTo.x = moveTo.x - 1; }
    11. if (moveDir.x > 0.3f) { moveTo.x = moveTo.x + 1; }
    12. if (moveDir.z < -0.3f) { moveTo.z = moveTo.z + 1; }
    13. if (moveDir.z > 0.3f) { moveTo.z = moveTo.z - 1; }
    14.  
    15. if (moveTo != oldMoveTo) {
    16.     transform.position = Vector3.MoveTowards(transform.position, moveTo, 0.2f);
    17.     }
    Can anyone tell me what I'm doing wrong? Thanks
     
  2. Panchos

    Panchos

    Joined:
    Oct 31, 2012
    Posts:
    34
    So it was just an error in line 12 and 13. All sorted... thread can be nuked