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. Dismiss Notice

Best way to properly handle a cursor using keyboard input?

Discussion in 'Scripting' started by hedgeh0g, Mar 20, 2021.

  1. hedgeh0g

    hedgeh0g

    Joined:
    Jul 18, 2014
    Posts:
    102
    Hello folks,

    So, imagine a menu of *any* game. Take as a reference the attachment to this post.
    We can see there is a cursor on the left of the Attack text, if the player wants to select any command, he would press right/left and expect the cursor to move depending on the input.

    The problem is, how would you move the cursor around and place it in a "precise" position of the left of the text? This is a fairly simple example, as we could just hardcode the position or something like that. But what if we have N rows and M columns? How would you reliably handle the cursor movement regardless of the number of choices you have on the menu?

    Thanks in advance.
     

    Attached Files:

  2. Mashimaro7

    Mashimaro7

    Joined:
    Apr 10, 2020
    Posts:
    723
    You could have an array of transforms, or rect transforms if this is a canvas, and have an index for whatever the current arrow is set to, and basically just set the position based on whatever that index is. So for example,
    Code (CSharp):
    1. void MoveCursor(int num){
    2. currentMenuIndex += num;
    3. cursor.transform.position = menuObjs[currentMenuIndex] + offset;
    4.  
    5. }
    So then, depending on which key you press, you can pass in 1 or -1. You would, of course, have to add in some checks for if the "currentMenuIndex" gets too high or goes below 0.

    You could even take out the "offset" and just simply have a bunch of empty game objects to mark which point the cursor should be at. And then in your select method, or enter, you could pass in the current menu index.

    That's one way to handle this, there's a million others, I'm sure.
     
  3. hedgeh0g

    hedgeh0g

    Joined:
    Jul 18, 2014
    Posts:
    102
    This was my first thought, and it's basically hardcoding. Which would bring problems if you try to run the game on different resolutions.
     
  4. Mashimaro7

    Mashimaro7

    Joined:
    Apr 10, 2020
    Posts:
    723
    Give it an anchor that covers the words, set the anchor to reposition with screen size, put the text under the same anchor. If they're all on your canvas, it should be fine.