I have a game with moving floating platforms. The simplest and most dynamic approach to achieve correct relative velocity is to simply make adjustments to the velocity. Here is a simplified version of what I do to achieve this.
In my game loop I have the following:
if heroOnBridge {
hero.extraMotion = floatingBridge.physicsBody!.velocity
} else {
hero.extraMotion = CGVector(dx:0,dy:0)
}
Here what I do is constantly look to see if my hero is on a moving bridge, if so then I set my hero's "extra motion" property to the velocity of the bridge that I am on. If I am not on a bridge then I don't add on any extra velocity. Note that I don't show how heroOnBridge is calculated because it really depends on how you define whether you are on a platform. In my case I assume you are on a platform if you intersect the platform frame and are on the ground.
Then in the area where I calculate my hero's velocity depending on his direction (left, right, jumping etc), I simply add on the extraMotion
to the hero's velocity.
If you don't already I suggest you have an area in the game loop for processing the motion of you characters. It will allow you to make changes to the velocity of your hero depending on certain factors (in the air, jumping, moving left/right, on a platform, etc.)
If you need more help with calculating the velocity part let me know and I will post more of my code. You may also want to read my answer here for smoothly and dynamically setting the velocity.
Remember, for the most part you never want to set the position of anything directly, always try to set the necessary velocity to achieve that position over some period of time. This prevents very jittery and unpredictable motion.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…