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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Why wont my Object go slower while pressing the button?

Discussion in '2D' started by Luez_, Dec 26, 2019.

  1. Luez_

    Luez_

    Joined:
    Dec 25, 2019
    Posts:
    4
    Heres the Code :

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour {
    6.  
    7.     float x = 1;
    8.     float y = 1;
    9.  
    10.     float notPressed= 10;
    11.     float pressedUp= 5;
    12.     float pressedDown = 20;
    13.  
    14.     void Start()
    15.     {
    16.        
    17.     }
    18.  
    19.     void Update()
    20.     {
    21.  
    22.         transform.Translate(x - x, y / notPressed, 0);
    23.  
    24.         if (Input.GetKey("w"))
    25.         {
    26.  
    27.             transform.Translate(x - x, y / pressedUp, 0);
    28.         }
    29.         else if (Input.GetKey("s")) {
    30.  
    31.             transform.Translate(x - x, y / pressedDown, 0);
    32.         }
    33.  
    34.     }
    35. }
    If you find out why the object wont go slower please write it down below.
    Thanks!
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,594
    What is the point of x-x ? Is 0 isn't it?

    Try add another else statement below line 32 and move line 22 there.

    Keep curly bracket consistency. See line 29.
     
    Luez_ likes this.
  3. Luez_

    Luez_

    Joined:
    Dec 25, 2019
    Posts:
    4
    The x-x is there because 0 didnt work for some reason.
    Im adding the other else statement later because its very late rn(2:20am).
    Telling you later if it worked!
     
  4. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,594
  5. PuppyPolice

    PuppyPolice

    Joined:
    Oct 27, 2017
    Posts:
    116
    I mean what happens is that the update function keeps setting transform.Translate(x - x, y / notPressed, 0); constantly.

    its like this
    1. set speed to notPressed.
    2. set speed to either w or s speed or no speed
    3. repeat step 1
    this happens around 30 to 1000 times a second, even if you hold down S or W it will first set the speed notPressed before setting it to one of the other.
     
  6. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,594
    Yep, this how you wrote the code.
    You ask basically to run transit, translate in every update.
    You may need change the logic, if you require different behavior.

    Like for example, setOnce translation, if button is not pressed, otherwise reset setOnce status, after button is released.