Search Unity

Moving 2.5D Character with recoil mechanic.

Discussion in 'Scripting' started by mikeholbrook95, Oct 11, 2018.

  1. mikeholbrook95

    mikeholbrook95

    Joined:
    Oct 11, 2018
    Posts:
    2
    Hi, I'm trying to figure out the best way to move a character, who also has a gun which applies a recoil force (to jump higher/shoot).

    Currently I'm moving the character using rigidbody.velocity in the FixedUpdate function, and then when the gun is fired I use AddForce opposite to the direction the gun is aiming. This works for moving the character when it's on the ground, however the recoil doesn't work and I think its because I'm setting the velocity relative to the input value every frame for left/right movement.

    I tried using AddForce instead to make the character walk left/right but the friction of the rigidbody on the floor gives an undesirable effect.

    The recoil mechanic works perfectly, and the issue seems to be to do with the way I'm moving the character left/right. I'd like the controls when on the ground to be quick and responsive, but can't figure out a way to do this without setting the velocity every fixed update.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,692
    You are correct: if you are driving the velocity manually, then forces don't have any impact.

    I suggest you keep a second "recoil velocity" term in your script, and when you fire, add an appropriate amount to that Vector3 object.

    Code (csharp):
    1. Vector3 RecoilVelocity;  // add to this when firing
    When you have player input, set it to a temporary Vector3 ("player velocity") instead of putting it straight into the Rigidbody.

    Code (csharp):
    1. Vector3 PlayerVelocity; // set this to Vector3.zero except when player motion control present.
    Finally, combine "player velocity" and "recoil velocity" (addition) and assign that to the rigidbody as you were each frame.

    Code (csharp):
    1. myRigidbody.velocity = PlayerVelocity + RecoilVelocity;
    Also, each frame, reduce that recoil velocity by a small amount so that it returns to zero fairly quickly, something like:

    Code (csharp):
    1. const float RecoilFadeRate = 3.0f;
    and in your update loop:

    Code (csharp):
    1. RecoilVelocity -= RecoilVelocity * RecoilFadeRate * Time.deltaTime;
    That might kinda get you closer to what you're looking for...
     
  3. mikeholbrook95

    mikeholbrook95

    Joined:
    Oct 11, 2018
    Posts:
    2

    Hi, thanks for the help! gonna try this out now and I'll report back.

    EDIT: Just tried this, and it seems like a step in the right direction. The only issue is, gravity no longer is applied to the rigid body, i believe its something to do with setting the y value to 0 in player velocity. I tried using the old velocity.y value in its place, however this compounds when adding it to the recoil velocity.
     
    Last edited: Oct 13, 2018