Unity2D: Using the left analogue stick to navigate through 2D space

55 Views Asked by At

I am a beginner in Unity and I'm trying to make something pretty simple. However, I don't know where to start. I have a number of 'knots' in the scene, that the player will be able to select. They will then be able to connect two knots. I managed to find all knots in a range of 40 from the player's position and put them in an array. The next step would be to 'navigate' through the knots. I want the player to use the left analogue stick for that, but I don't know how to go about it. When they hold the stick at 120°, the knot closest to that position would be able to be selected by pressing another button. I looked at some UI navigation scripts, but this situation is pretty different as it's a two dimensional space. Does anyone have any suggestion on how to go about this? Thank you.

screenshot

1

There are 1 best solutions below

2
Mav On

It sounds to me like you're going to have to do some trigonometry to be able to find the nearest "knot." Each of these--at least if you're programming well--should each be an object whose x and y location variables can be accessed from your script.

You could iterate through the list of collected objects and compare them to your current location and store the object in a temporary variable if it is a shorter distance than the last object in the array.

Here's some pseudocode that should help illustrate my point:

for item in array {

    Object closestKnotDist = Null

    Float currentKnotDist = math.sqrt((player.x-item.x)**2 + (player.y-item.y)**2)

    if currentKnotDist < closestKnotDist {
        closestKnotDist = currentKnotDist
    }

}

Thus, closestKnotDist will be the closest object to the player. Manipulate it how you will.

Not sure if this answered your question, but feel free to add some more explanation if not!