- Home /
How to mix velocity with addForce?
Guys, I have constant movement in the X axis and when jump key is pressed there is an AddForce that adds force to the Y axis, but how can I add force also in the X axis so the jump feels more natural?
I can't do it right now because o my velocity set is overriding the X addForce.
Here is my movement code:
void FixedUpdate()
{
rigidbody.velocity = new Vector3(speed.initialSpeed, rigidbody.velocity.y, 0);
if(!onGround)
{
this.rigidbody.AddForce(new Vector3(0,-gravity,0));
}
if(jump)
{
rigidbody.velocity = new Vector3(rigidbody.velocity.x, 0, 0);
rigidbody.AddForce(jumpForce, ForceMode.VelocityChange);
jump = false;
}
}
Thanks!
Answer by ScroodgeM · Aug 21, 2012 at 09:16 PM
instead of apply new force instantly, just calculate speed offset needed in whole FixedUpdate method.
at the end of method apply offset with ForceMode.VelocityChange
something like
void FixedUpdate() { Vector3 speedChangeNeeded = Vector3.zero;
speedChangeNeeded.x = speed.initialSpeed - rigidbody.velocity.x;
if (!onGround)
{
speedChangeNeeded.y = -gravity;
}
if (jump)
{
speedChangeNeeded.y = jumpForce;
jump = false;
}
rigidbody.AddForce(speedChangeNeeded, ForceMode.VelocityChange);
}
Can you please post a code sample? I've tried this calculation without success.
Thanks! With some modifications I was able to correctly use your code to achieve the effect.
Your answer
Follow this Question
Related Questions
AddForce vs Velocity issues with Rigidbody2D 2 Answers
Rigidbody not calling OnCollisionEnter 1 Answer
Moving a camera with AddFoce, or setting velocity, need help 1 Answer
Rigidbody Enemy and Collisions 2 Answers
2D metroid boost ball 0 Answers