Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Greywize · Jan 08, 2019 at 10:48 AM · 2dmovementtopdown

Add acceleration and deceleration for top down 2D movement.

Yo! I'm relatively new to Unity. I want to smooth out my movement a bit by adding a small acceleration/deceleration effect when moving. Basically, I want to have my speed variable go from 0 to max speed in a short amount of time and back to 0 when stopping/letting go of the movement key(s). I've searched for a decent two hours for a solution but so far, none of them work with the script I got from a tutorial. Here is the script.

 using UnityEngine;
 
 public class Movement : MonoBehaviour
 {
     Rigidbody2D body;
     float horizontal;
     float vertical;
     float moveLimiter = 0.7f;
 
     float moveSpeed = 7.5f;
     
     void Start()
     {
         body = GetComponent<Rigidbody2D>();
     }
     void Update()
     {
         //Aquire input
         horizontal = Input.GetAxisRaw("Horizontal");
         vertical = Input.GetAxisRaw("Vertical");
     }
     void FixedUpdate()
     {
         //Check if character is moving diaginally
         if (horizontal != 0 && vertical != 0)
         {
             //Average out speed for simultaneous inputs.
             body.velocity = new Vector2((horizontal * moveSpeed) * moveLimiter, (vertical * moveSpeed) * moveLimiter);
         }
         else;
         {
             body.velocity = new Vector2(horizontal * moveSpeed, vertical * moveSpeed);
         }
     }
 }

Currently, the character goes from standing still to immediately taking off at the speed I specified. I want it to accelerate from 0 to max speed and then back to 0 once I let go of the movement keys.

I realise this question has been posted several times but trust me when I say, I went through them all. I know lerp is a thing (And slerp, smoothStep, etc) but I couldn't figure them out. At least, I couldn't get them working with this script.

Some help would be greatly appreciated.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by Ady_M · Jan 08, 2019 at 02:15 PM

Before you even think about moving an object, focus on just getting a float value to increase towards max while a key is pressed and drop to towards zero when the key is up.

 

This example also lets you go under 0, in case you need that.

 

To test it, place the script on an empty object and use the controls A (negative) and D (positive), and Shift to reach the destination value twice as fast.

 

Max in this case is always -1 or 1. You can easily multiply this by any number as needed (for example, multiply it by maxSpeed then translate the object).

 public float value;
 public float timeFromZeroToMax = 2;  // How long it takes to reach max


 private void Update ()
 {
     float moveTowards = 0;
     float changeRatePerSecond = 1 / timeFromZeroToMax * Time.deltaTime;

     if (Input.GetKey (KeyCode.A))
     {
         moveTowards = -1.0f;
     }
     else
     if (Input.GetKey (KeyCode.D))
     {
         moveTowards = 1.0f;
     }

     if (Input.GetKey (KeyCode.LeftShift))
     {
         // Reach destination value twice as fast
         // when Shift is held down
         changeRatePerSecond *= 2;
     }

     value = Mathf.MoveTowards (value, moveTowards, changeRatePerSecond);
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Klarzahs · Jan 08, 2019 at 02:28 PM

Hi @RealmsDev , you can achieve this by faking a very basic acceleration. A (untested) code snippet for this would be:

 float acceleration = 1;
 float curHorizontalMovement = 0;
 float curVerticalMovement = 0;
 flaot MinMovement = 0.001f;
 
 ...
 
 void FixedUpdate(){
  if(horizontal != 0)
  //accelerate in direction of keypress
   curHorizontalMovement += acceleration * horizontal;
 else
 //we dont detect any keypress: "decay" the velocity by half
   curHorizontalMovement  /= 2;
 //if we keep decaying, we will walk for a long time, but always slower. To combat this, we simply set a minimum threshold
 if( curHorizontalMovement  < MinMovement)
  curHorizontalMovement  = 0;
 
 //similar for the vertical movement
 ...
 body.velocity = new Vector2(curHorizontalMovement  * moveSpeed, curVerticalMovement* moveSpeed);
 }

This approach has multiple downsides:

  • It doesn't feel natural: most acceleration isnt linear in the real world

  • If you are walking at fullspeed in one direction and want to do a 180, you would need to decelerate and then accelerate in the opposite direction. This takes time

  • Decaying the velocity by half if you dont have any input is unnatural as well

As a side node: you dont want to check for zero for a float with "= 0", as this is nearly never the case (explanation). Instead, set a threshold, under which you just assume it to be zero. Hope this helps

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

234 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Character movement problem, floats away 1 Answer

(2D Movement) How do I make my sprite move up, down, left, and right, without moving diagonal? 1 Answer

Top-down movement in 2D 1 Answer

2D Directional top down movement,Topdown 2d Directional Movement 0 Answers

2D Topdown movement without sliding 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges