Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Unity 2D Touch Game for Android Script, jump and move not working very well

Discussion in 'Scripting' started by Hazax, Aug 1, 2019.

  1. Hazax

    Hazax

    Joined:
    Jul 22, 2019
    Posts:
    1
    Hi guys, at first, sorry if something say`s should be wrong, cause i`m not EN speaker.

    Well, i`m trying to make my first 2D game.
    The pourpose was very simples, when the user touches the screen, the character jump and move at the point.

    The code bellow works for a little, i only make some changes on another script that i used on touch...

    The problem with this is the velocity only changes when touch righ or left of screen.
    I know they get ScreenWorldPos, and soo my game and character starts exactly on position x = 0...
    I read another ways to write the script, but they don`t use velocity or jump and i like that way alread is.
    The problem specificly is when the character is on the left os screen, and the user touches left screen too, but at right os character, is an specific area, but it confuses the users.

    Code (CSharp):
    1. private void Update()
    2.     {
    3.         if (Input.anyKeyDown) // i will change this for touch, its only for test on emulator
    4.         {
    5.             TouchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    6.             rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Force);
    7.             rb.velocity = new Vector2(TouchPos.x, rb.velocity.y);
    8.         }
    9.     }
    I`ve tryed to make a if that should correct it... something like that...

    Code (CSharp):
    1.             if (TouchPos.x > 0 && PlayerWorldPos.x > 0 && TouchPos.x < PlayerWorldPos.x)
    2.             {
    3.                 rb.velocity = new Vector2(-TouchPos.x, rb.velocity.y);
    4.             }
    5.             else
    6.                 if (TouchPos.x < 0 && PlayerWorldPos.x < 0 && TouchPos.x > PlayerWorldPos.x)
    7.             {
    8.                 rb.velocity = new Vector2(-TouchPos.x, rb.velocity.y);
    9.             }
    10.  
    11.             rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Force);
    12.             rb.velocity = new Vector2(TouchPos.x, rb.velocity.y);
    13.         }
    soo my logic says, if the character position is negative and screentouch is negative too, but biggest than character position, soo the velocity should be positive.
    I apllyed the same logic from the same problem on right screen... If character is on positive screen, touches too, but lowerst than character, soo, i`ve tryed to invert velocity positive to negative.

    Well, in resuming this don`t as work, sometimes he go to another position, sometimes no, has various bugs afeter 3 days trying do this for myself.

    Well is it, thanks for the help