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

Discussion and feedback on Construct 2

### » Tue Mar 17, 2015 3:58 am

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...
B
26
S
9
G
2
Posts: 534
Reputation: 4,678

### » Tue Mar 17, 2015 8:08 am

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.
B
82
S
26
G
63
Posts: 4,857
Reputation: 45,754

### » Tue Mar 17, 2015 9:40 am

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.
B
90
S
30
G
24
Posts: 3,189
Reputation: 32,455

### » Tue Mar 17, 2015 9:23 pm

@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.
B
26
S
9
G
2
Posts: 534
Reputation: 4,678