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. Dismiss Notice

2D Acceleration When I Hit Space Button C#

Discussion in 'Scripting' started by n9ne, Feb 4, 2015.

  1. n9ne

    n9ne

    Joined:
    Feb 4, 2015
    Posts:
    2
    Can anyone give me code to make the player accelerate when i hit space button and disable the acceleration when i hit space button again :)
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
  3. Crayz

    Crayz

    Joined:
    Mar 17, 2014
    Posts:
    192
  4. n9ne

    n9ne

    Joined:
    Feb 4, 2015
    Posts:
    2
    Can anyone write it for me ?
     
  5. Crayz

    Crayz

    Joined:
    Mar 17, 2014
    Posts:
    192
    It's a fairly simple script, I recommend you dig into the Learn section so you understand what the code in your game is actually doing.

    To get you started, in your Update() method you can call Input.GetKeyDown() to check if a player presses space. If true, toggle a boolean that determines whether the object should be accelerating or not.
    Code (csharp):
    1. private bool shouldAccelerate = false;
    2.  
    3. void Update()
    4. {
    5.      if(Input.GetKeyDown(KeyCode.Space))
    6.      {
    7.           shouldAccelerate = !shouldAccelerate;
    8.      }
    9.      if(shouldAccelerate)
    10.      {
    11.           // do your acceleration here
    12.      }
    13. }
     
    Mike-Geig likes this.
  6. Mike-Geig

    Mike-Geig

    Unity Technologies

    Joined:
    Aug 16, 2013
    Posts:
    220
    Just chiming in to say that Crayz's solution will work for you. If the solution doesn't make sense, be sure to go to the Learn page and watch some of the beginner scripting videos.