I’m trying to set up a vehicle that moves like a train, where a comparatively small engine slowly accelerates the engine car and any attached cargo cars until they’ve attained some maximum speed. I’m manually setting Rigidbody.velocity instead of using AddForce, so I’ve been accomplishing the acceleration piece by lerping the velocity from its current value towards the desired value at a rate determined by acceleration. That doesn’t feel unpleasant, but it does feel very non-train-y. It’s smooth, and even if I reduce the acceleration and top speed by a function of the number of cargo cars it has in tow, it doesn’t really feel like you’re hauling weight behind you.
I feel stupid trying to do this manually, since unity has a pretty great physics system, but I’m a bit lost on how I should be approaching this- right now the engine car is the only rigidbody that moves, and all the cargo cars are rigidbodies that are connected to the engine car (or each other) with hinges. I can pretty easily convert between the weight of cargo held in each car and that rigidbody’s mass, but is there a genuinely straightforward way to translate that into useful behavior? Or should I stick with fine-tuning the throttle behavior until it feels right?
If you apply a constant force, the object will accelerate. Acceleration = Force / Mass. If all the cars and the engine already have masses assigned to them, you should be able to just assign a constant force to the engine car. Change the Drag on its RigidBody to set its max velocity. The higher the Drag, the lower the max velocity. To do a constant force, you have to put the call in FixedUpdate:
rigidbody.AddForce(engineForceVector);
Or you can use the “ConstantForce” helper component.
Oh, that’s an interesting idea; I originally picked directly manipulating velocity over AddForce so I could do my throttle lerp/PID-y thing, but I like the idea of keeping this entire system constrained to physics.
Is there any practical difference between AddForce(someValue) in fixed update, or using the constant force component and editing it from an external script every time the player changes vehicles?
I believe it is the same. If you use AddForce() you have to put it in FixedUpdate so that it gets called every frame, but if you use ConstantForce you just fill out the numbers in the inspector and it automatically does it every frame for you. You just change the values in ConstantForce to change directions.