I’m using logic based off the FPS RigidBody walker in the wiki so I have a snappy, clamped, rigidbody controller.
The input to movement goes like this:
// Get Input()
inputVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
inputVector.Normalize();
targetDirection = transform.TransformDirection(inputVector);
targetVelocity = targetDirection;
targetVelocity *= airControl;
// Apply a force that attempts to reach our target velocity
Vector3 velocity = rigidbody.velocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
The problem is when I want to jump the same logic makes the character slow down to a stop in the air instead of preserving the momentum. Since I have a slower speed for in-air movement, even if I press in the direction of the jump it slows down from the intial speed I had when I pressed jump.
I want to preserve the original speed vector at the moment of jumping while also applying the above logic for any additional and precise air movement.
I understand I need to save the original speed, find the component of my input vector that is parallel to the original speed and take it into account somehow. In words:
- Take my input vector’s component that is parallel to the original speed (project the input on the speed)
- If the projected component is in the same direction of the speed, ignore it when calculating velocityChange ( I still want to be able to slow down if my input is in the opposite direction )
What I can’t figure out is how to take the projected component into account so it will be ignored when calculating the velocityChange:
// Start Jump
originalSpeed = new Vector3(rigidbody.velocity.x, 0, rigidbody.velocity.z);
rigidbody.velocity = new Vector3(rigidbody.velocity.x, CalculateJumpVerticalSpeed(), rigidbody.velocity.z);
// Project input on original speed vector
Vector3 projectedInput = Vector3.Project(targetVelocity, originalSpeed.normalized);
float dotProduct = Vector3.Dot(projectedInput, originalSpeed);
// Take into consideration the projectedInput in case it is parallel to originalSpeed
if(dotProduct == 1)
// ????????????