4
\$\begingroup\$

I am trying to add force to the player's rigidbody, when the screen is held. I've written the following code:

float PlayerForce=50.0f;

void FixedUpdate()
{
   bool PlayerActive = Input.GetButton ("Fire1");

   if (PlayerActive) {
       PlayerRigidBody.AddForce (new Vector2 (0, PlayerForce));
   }
}

This does not add a smooth jump effect. I've searched for smooth force effect, but I didn't find anything useful. How do I add a smooth force my player's rigid body, to make them jump?

\$\endgroup\$
  • 1
    \$\begingroup\$ Can you describe what you mean by "smooth" in this context? In what way is the current result lacking "smoothness"? \$\endgroup\$ – DMGregory Oct 18 '16 at 12:47
  • \$\begingroup\$ Why are you using GetButton instead of GetButtonDown? \$\endgroup\$ – Vadim Tatarnikov May 5 '17 at 6:31
1
\$\begingroup\$

Use the AddForce like below and reduce PlayerForce value.

PlayerRigidBody.AddForce (new Vector2 (0, PlayerForce), ForceMode.Impulse);
\$\endgroup\$
  • 1
    \$\begingroup\$ Since this is being triggered based on GetButton (which returns true over a span of frames) not GetButtonDown (which triggers only on the initial press), ForceMode.Impulse is not the best choice here. It represents an instantaneous acceleration, rather than a continuous push over time. Using impulse instead of force here will cause the behaviour to change when you change the timestep, while ForceMode.Force will correct for this. That said, applying an initial impulse only once when the jump begins is generally a good plan, as that is an instantaneous action. \$\endgroup\$ – DMGregory Oct 18 '16 at 12:50
  • 1
    \$\begingroup\$ Yep. It will cause issue as the input spans multiple frames. For jump, shoot like features impulse worked for me, single press input. But it's a great idea using impulse once and rest using force, should solve the op's problem. \$\endgroup\$ – Sourav Paul Oct 18 '16 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.