Search code examples
javascriptmathgame-physics

Add Velocity Relative To Object


I am trying to make a train in js but i want add the velocity to the train. but the train has an other axis relative to the canvas so how can i add the velocity relative to canvas http://snapsoft.eu/example.png


Solution

  • If train system is rotated relative to stationary system by angle Theta, then you can transform velocity vector Vr (in rotated) to Vs (in stationary):

    Vs.X = Vr.X * Cos(Theta) -  Vr.Y * Sin(Theta)
    Vs.Y = Vr.X * Sin(Theta) +  Vr.Y * Cos(Theta)
    

    If rotated system moves with velocity W, then add W also

    Vs.X = W.X + Vr.X * Cos(Theta) -  Vr.Y * Sin(Theta)
    Vs.Y = W.Y + Vr.X * Sin(Theta) +  Vr.Y * Cos(Theta)
    

    In your example

    Theta = -Pi/4
    Vs.X = 0.5 * 0.707 +  0 * 0.707 = 0.3535
    Vs.Y =  - 0.5 * 0.707 +  0 * 0.707 = -0.3535