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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Is it possible to cap the addForce given without capping the max velocity?

Discussion in 'Scripting' started by LMacalister, Apr 20, 2020.

  1. LMacalister

    LMacalister

    Joined:
    Jul 5, 2017
    Posts:
    9
    Making a grapple hook swing game set in space (0 gravity) and I want the player to have some limited movement when floating without gravity (think of like weak boosters). I tried setting the velocity for the moving but then the momentum of the swing is lost so I've decided to use add force but the problem with that is there's no cap on the force so the "boosters" it ends up being really fast/powerful. If I cap the velocity as all the answers on here say then it'll cap the momentum from the grapple swing (core component) so I need a way to cap the actual force added but can't find a way to do that and Mathf.clamp doesn't seem to work with addForce.


    Float movement code below:

    Code (CSharp):
    1. else if (!groundCheck)
    2.                 {
    3.                     curSpeed = floatSpeed;
    4.                     rBody.AddForce(new Vector2(Mathf.Lerp(0, Input.GetAxis("Horizontal") * curSpeed, 0.8f), Mathf.Lerp(0, Input.GetAxis("Vertical") * curSpeed, 0.8f)));
    5.                 }
    I can post the grapple code if needed but it's quite big.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,970
    Generally in order to reason about an engineering problem you want to stay clear of code written like line 4 above.

    That line has two separate axes of input being collected, then scaled, then I'm not really sure what you're doing with the lerping, and finally AddForce is being called with ... something.

    Overall I honestly stare at that and throw my hands up.

    Break it down so you do one thing at a time, one statement per line, assigning to meaningful temporary variables to help you reason about it: gather the input, scale it, lerp it (I don't think that is doing what you think the code above), and at each stage you can print the values out so you can see what's happening in real time as you play.
     
    PraetorBlue likes this.
  3. LMacalister

    LMacalister

    Joined:
    Jul 5, 2017
    Posts:
    9
    Good point I was messing around with stuff but hadn't changed it as it worked.

    Here is what I've changed it to. The two inputs are set in update while the Vector2 movement and add force is in fixed update.


    horizontalInput = Input.GetAxis("Horizontal");
    verticalInput = Input.GetAxis("Vertical");

    Vector2 movement = new Vector2(horizontalInput, verticalInput);
    rBody.AddForce(movement * curSpeed);