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

Discussion and feedback on Construct 2

Post » 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...
Image
B
32
S
11
G
2
Posts: 563
Reputation: 5,096

Post » 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
88
S
30
G
89
Posts: 5,113
Reputation: 60,337

Post » 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
92
S
31
G
24
Posts: 3,191
Reputation: 32,644

Post » 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.
Image
B
32
S
11
G
2
Posts: 563
Reputation: 5,096


Return to Construct 2 General

Who is online

Users browsing this forum: No registered users and 7 guests