Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

The way I move my character messes up other physics calculations

Discussion in 'Scripting' started by danigipsh1, Dec 7, 2018.

  1. danigipsh1

    danigipsh1

    Joined:
    Jun 8, 2018
    Posts:
    2
    Hi, I'm trying to create a 2D platformer and I've run into a small problem. I move my character by changing the rigidbody2d velocity directly, I tried to use the AddForce method but I don't like the way it feels. I've also tried to implement an ability that when used by the player, it applies a kickback using AddForce. My problem is that because of how I made the player move, the acceleration caused by the force is discarded the next time my horizontal movement function is executed.
    Here's my code if it helps:

    Horizontal Movement
    Code (CSharp):
    1. void MoveHorizontal()
    2.     {
    3.         horizontalAxis = Input.GetAxisRaw("Horizontal");
    4.         rb.velocity = new Vector2(horizontalAxis * speed, rb.velocity.y);
    5.     }
    Kickback
    Code (CSharp):
    1. void PushBack(int pushDirection, float pushBackForce)
    2.     {
    3.         rb.AddForce(pushDirection * Vector2.right * pushBackForce, ForceMode2D.Impulse);
    4.     }
    Thank you in advance! :)
     
  2. Vega4Life

    Vega4Life

    Joined:
    Nov 27, 2012
    Posts:
    12
    I would assume if the character had pushBack, you would want it to complete before you can move again. If this is the case, add a bool isPushBack (or whatever you want to name it). Set it to true in the PushBack function. Add an if statement in the MoveHorizontal checking if the character isPushBack. Create a coroutine as a timer to set the bool back to false, and call it within the PushBack function.

    This will let the PushBack do its work, then give control back to the user so they can move again.
     
  3. danigipsh1

    danigipsh1

    Joined:
    Jun 8, 2018
    Posts:
    2
    Thank you for you idea, I'll try it.
     
  4. SparrowsNest

    SparrowsNest

    Joined:
    Apr 6, 2017
    Posts:
    1,491
    Could also add velocity instead of explicitly setting it and clamping it if it's over the max speed
     
  5. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    6,124
    Another option would be to have the velocity move towards a specific value.

    Code (csharp):
    1. horizontalAxis = Input.GetAxisRaw("Horizontal");
    2. Vector3 targetVelocity = new Vector2(horizontalAxis * speed, rb.velocity.y);
    3. rb.velocity = Vector2.MoveTowards(rb.velocity, targetVelocity, someAccelerationValue);
    You could alter someAccelerationValue and, for example, make it lower when your character has just been hit by the PushBack effect, but very high in normal circumstances to preserve your snappy movement. That way your players will not feel completely powerless after PushBack, but still a little bit hampered.