#Rigidbody player movement upon moving rigidbody

3 messages · Page 1 of 1 (latest)

dim dagger
#

I am trying to create a system in which the player may move freely upon the vehicle while said vehicle is itself in movement, both accelerating, decelerating and turning. The player's relative velocity with respect to the vehicle should generally be zero. If the player moves, the relative velocity should the player's velocity on a stationary frame of reference. If the vehicle accelerates too much, say 5m/s^s, this system should only compensate a determined amount, for instance 3m/s^2 which would result in a net acceleration of 2m/s^2. How can I implement this as simply as possible?

#

        private void UpdateMovement(float deltaTime)
        {
            float targetSpeed = m_Sprint ? sprintSpeed : walkSpeed;
            float targetAcceleration = m_Sprint ? Mathf.Lerp(walkAcceleration, sprintAcceleration, Mathf.InverseLerp(0f, m_LocalVelocity.magnitude, targetSpeed)) : walkAcceleration;
            float realAcceleration = m_IsGrounded ? targetAcceleration : airAcceleration;

            Vector3 targetLocalVelocity = (root.right * m_MoveDirection.x + root.forward * m_MoveDirection.y).normalized * targetSpeed;

            m_LocalVelocity = Vector3.MoveTowards(m_LocalVelocity, targetLocalVelocity, realAcceleration);

            Vector3 velocityDifference = Vector3.ClampMagnitude(m_LocalVelocity - rigidbody.velocity, realAcceleration * deltaTime);
            velocityDifference.y = 0f;

            rigidbody.AddForce(velocityDifference, ForceMode.VelocityChange);
        }
        private void CompensateVehicleMovemet()
        {
            if (m_VehicleRigidbody == null)
                return;

            //  Calculate velocity difference
            Vector3 vehicleVelocityChange = m_VehicleRigidbody.velocity - m_LastVehicleVelocity;
            Vector3 playerVelocityChange = rigidbody.velocity - m_LastPlayerVelocity;
            Vector3 velocityChange = vehicleVelocityChange - playerVelocityChange;

            //  Only compensate a determined amount of velocity change
            Vector3 clampedVelocityChange = Vector3.ClampMagnitude(velocityChange, maximumVelocityChange);

            //  Apply velocity change
            rigidbody.AddForce(clampedVelocityChange, ForceMode.VelocityChange);

            m_LastPlayerVelocity = rigidbody.velocity;
            m_LastVehicleVelocity = m_VehicleRigidbody.velocity;
        }

Here is what I currently have (a fraction of the script, probably the only noteworthy part, but I can share more if necessary)

#

I should also note that I wish the player not to be able to push the vehicle but viceversa to be possible (probably solved using a kinematic rigidbody on the vehicle with a copy of all the colliders and layer masking)