I have a simple 2D game where I can move an object using the mouse. I've been improving on the 'feel' of the movement gradually, however it still doesn't behave as you'd expect if the object were to be moved by human hands in a real-world scenario. My improvements were as follows:
New position = mouse position Sharp unrealistic movement. No max speed.
Cap the maximum speed Nicer. Still stops abruptly. Doesn't accelerate smoothly
Add 'inertia', recording last change in position and applying it to subsequent moves
Vastly improved, however...
- Object is dragged as if on elastic, slow to accelerate, very slow to stop.
- Once moving, object oscillates or orbits around a stationary mouse position.
I'm looking for suggestions on how to make the movement more intuitive:
- Moving an object from A to B a human would rarely overshoot
- A user shouldn't need to correct against inertia to stop an object
- I'd like to be able to adjust the weight of the object so that heavier things are harder to get moving
My current code is as follows:
float maxInertiaChange = 0.1;
Vector2 lastPosition = Vector2.negativeInfinity;
Vector2 inertia = Vector2.zero;
private Vector2 InterpretPosition(Vector2 mousePosition) {
Vector2 newPosition;
if (lastPosition.x != float.NegativeInfinity) {
newPosition = lastPosition + (inertia * Time.deltaTime);
newPosition = GetPointTowardsTargetWithMaxDistance(newPosition, mousePosition, maxInertiaChange);
inertia = (newPosition - lastPosition) / Time.deltaTime;
} else {
newPosition = mousePosition;
}
lastPosition = newPosition;
return newPosition;
}
private static Vector2 GetPointTowardsTargetWithMaxDistance(Vector2 startVector, Vector2 targetVector, float maxDistance) {
float lerpScale = maxDistance / Vector2.Distance(startVector, targetVector);
return Vector2.Lerp(startVector, targetVector, lerpScale);
}
Thanks in advance!