Search code examples
c#unity-game-enginemobilegame-engine

unity swipe right and left bug


hello everyone and thanks for the help, I am creating a mobile game in unity that requires left and right swiping to move (subway surfers style) now the code is working just alright but when I start the game the player always shifts and starts on the very left lane and not stays in the middle as I want him to (after he shifts you can swipe just fine) any clues on how to fix it?

the code :

  private float startpos;
    private int pos;
    public float[] positionsset;
    public GameObject player;
    private Vector3 velocityf = Vector3.zero;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {

        
        if (Input.GetMouseButtonDown(0))
        {
            startpos = Input.mousePosition.x;
        }
        /////////////////////////////////////////////////////
        else if (Input.GetMouseButtonUp(0))
        {
            if (Input.mousePosition.x - startpos > 0 && pos < 2)
            {
                pos++;
            }
            else if (Input.mousePosition.x - startpos < 0 && pos > 0)
            {
                pos--;
            }
        }

        player.transform.position = Vector3.SmoothDamp(player.transform.position, new Vector3(positionsset[pos], player.transform.position.y, player.transform.position.z), ref velocityf, 0.1f);

    }
}

Solution

  • You are not initializing pos to anything, so it will be set to its default value which is 0. Since 0 indicates the left lane, that is the one it will start on. Simply change int pos; to int pos = 1; and it should start on the middle lane. Alternatively, you could make pos a public variable and set its value in the inspector, which makes it easier to tweak if you ever want to start in another lane.