For the math folks... Which is better? Projection

0 favourites
  • 4 posts
From the Asset Store
Aliens are invading our planet! Solve the math question, and attack the alien with your laser. Covers addition, subtract
  • Okay,

    These are my givens:

    v = (x,y)

    v2 = ?

    a = The angle between v and v2

    I want to solve for the projection (P) of v onto v2.

    I have two ways I can do this (that I know of).

    a.)

    P.X = (v.X * cos(a)) + (v.Y * sin (a))

    P.Y = (v.X * cos(a+pi/2)) + (v.Y * sin(a+pi/2))

    b.)

    v2.magnitude = sqrt ( v2.X^2 + v2.Y ^2 )

    v2.unitVector = v2 / v2.magnitude

    DotProduct = v.X * v2.X + v.Y * v2.Y

    P = DotProduct * v2.unitVector

    Which is better? More efficient, etc...

  • Whichever works, the first one doesn't look right to me, but I haven't tested it.

    I suppose sin and cos are relatively more expensive to compute from what I know, then again so can sqrt. You can simplify the equations and use trig identities such as cos(a+pi/2))=-sin(a) then re-arrange stuff so you only calculate stuff once that's used many times.

    But all that may be a futile effort. The best way to see which is more efficient is by profiling it.

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • You'll run into trouble using pi/2 in C2, remember all its angles are based on degrees.

    And in cases where performance difference is marginal, like here, always go with the simpler/more concise option.

  • R0J0hound ... I imagined you would be first to answer. The first one works so long as you use degrees and not radians. The whole data oriented approach sounds good though. I will build some testers for this and find out. I had always heard sqrt() was slow but I figured it might be faster than multiple calls to sin or cos.

    sqiddster - I never cared much until I wanted to create a small library and wanted to make sure I do things the most efficient way. If I can... Just so it doesn't bite me somewhere down the road.

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)