2

Hi everyone Newbie here.

Top-down Zelda style game.

I'm trying to figure out how to make my player build speed to max speed then reduce speed to stoping.

I already have movement with GetRawAxis but my char moves at max speed the moment I press move with this method.

private void PlayerMovement()
{
    var playerMovement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * Time.deltaTime * moveSpeed;

    transform.position = new Vector3(
        transform.position.x + playerMovement.x,
        transform.position.y + playerMovement.y,
        transform.position.z);
}
Tas7e
  • 25
  • 1
  • 1
  • 4
  • 1
    Please provide Code and/or more info – Milos Romanic Sep 23 '19 at 14:06
  • Instead of setting velocity, you could try using the RigidBody's `AddForce` in the direction of the stick, and add some drag to cause him to stop slowly if no force is being actively applied – Ahndwoo Sep 23 '19 at 14:07
  • Here's my current movement method private void PlayerMovement() { var playerMovement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * Time.deltaTime * moveSpeed; transform.position = new Vector3( transform.position.x + playerMovement.x, transform.position.y + playerMovement.y, transform.position.z); } – Tas7e Sep 23 '19 at 14:12
  • Sorry Don't know how to make the code look properly – Tas7e Sep 23 '19 at 14:13
  • So if I add force it creates drag at the beginning and the end of movement @Ahndwoo? – Tas7e Sep 23 '19 at 14:15
  • @Tas7e, did you figure it out? – Hbarna Sep 26 '19 at 08:07
  • 1
    @Tas7e Hey I saw the question you just deleted here: https://stackoverflow.com/questions/67320573/jumping-with-no-change-direction-in-air I was about to post an answer so here it is anyway hope it helps https://pastebin.com/6ZRed1eu – dekajoo Apr 29 '21 at 16:08

2 Answers2

2

Here is a scenario where you can move your object in the x axis, gradually increasing the speed. You can do the same with the slowing down. Gradually decrease the speed by a value.

float acceleration = 0.6;
float maxSpeed = 30;
float speed = 0;

void Update(){
   if(speed < maxSpeed){
      speed += acceleration * Time.deltaTime;
    }

   transform.position.x = transform.position.x + speed*Time.deltaTime;

}
Hbarna
  • 425
  • 3
  • 16
  • 1) this only applies motion on the X axis 2) does not take into account player input and 3) doesn't include deceleration. – Draco18s no longer trusts SE Sep 23 '19 at 16:07
  • Yes I know it doesn’t do any of that but that’s the point. I’m just pointing him to the right direction. He can apply the logic to other scenarios. – Hbarna Sep 23 '19 at 16:13
0

You could try Vector3.SmoothDamp.

This uses a Vector storing the current "speed" and dumps it slowly.

Example can be found here: https://docs.unity3d.com/ScriptReference/Vector3.SmoothDamp.html

BooNonMooN
  • 250
  • 3
  • 13