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

0 Favourites
• 4 posts
• 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.

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)