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

Charachter Faster Than It Should!

Discussion in '2D' started by shatotti, Feb 8, 2016.

  1. shatotti

    shatotti

    Joined:
    Jul 7, 2015
    Posts:
    2
    Hello everyone,
    I'm making a 2D Runner game and trying to activate my charachter's "Run" animation and movement with the first touch on the screen.(Also with left mouse stick for test!) but when I click the right button the charachter translates his x position multiplied with 10 ,every second and it goes faster.I'm really new to Unity and Unity scripting so my script may have a lot of problems :/ .Here's my script:

    Code (CSharp):
    1. public GameObject obj;
    2.     public Transform player;
    3.     public Animator anim;
    4.     public int isTrue = 0;
    5.  
    6.     void Start()
    7.     {
    8.         anim = GetComponent<Animator>();
    9.         anim.Play("Idle");
    10.     }
    11.  
    12.     void Update()
    13.     {
    14.         foreach (Touch touch in Input.touches)
    15.         {
    16.             if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
    17.             {    
    18.                     anim.Play("Run");
    19.                 isTrue = 1;
    20.                 }
    21.             }
    22.  
    23.         if(Input.GetMouseButtonDown(1))
    24.         {
    25.             anim.Play("Run");
    26.             isTrue = 1;
    27.         }
    28.  
    29.         if (isTrue == 1)
    30.         {
    31.  
    32.             player.transform.Translate(player.transform.position.x+1, 0, 0);
    33.  
    34.         }
    35.         }
    36.  
    37.    
     
  2. KrayZLogic

    KrayZLogic

    Joined:
    Jun 19, 2013
    Posts:
    55
    You need to take frame time into account when doing the translation. Create a float variable for speed and adjust it until you get the speed you want. Try:

    player.transform.Translate(Time.deltaTime * speed, 0f, 0f);
     
  3. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    The problem is this line
    Code (csharp):
    1. player.transform.Translate(player.transform.position.x+1, 0, 0);
    The parameter for Translate is the translation desired, not the position desired.
    Also, you should multiply the movement by Time.deltaTime to keep your gameplay framerate independent.

    It should be
    Code (csharp):
    1. player.transform.Translate(1*Time.deltaTime, 0, 0);
     
  4. shatotti

    shatotti

    Joined:
    Jul 7, 2015
    Posts:
    2
    I've did it! Thanks a lot all of you!I just wrote that as you suggest:
    Code (CSharp):
    1.  if (isTrue == 1)
    2.         {
    3.  
    4.            transform.Translate(3*Time.deltaTime, 0, 0);
    5.          
    6.         }