Syntax Question

Why do we wrap the expression in an extra set of parenthesis in

capsuleCollider.offset = new Vector2((Mathf.Lerp(1f, laserRange, linearT)) / 2, capsuleCollider.offset.y);

I’d guessed the answer to the challenge was

capsuleCollider.offset = new Vector2(Mathf.Lerp(1f, laserRange, linearT) / 2, capsuleCollider.offset.y);

but it looks like I got tripped up somewhere.

Thanks!

1 Like

This is because when you wrap the expression in an extra set of parentheses you explicitly define the order of operations, this helps prevent confusion in the code.

capsuleCollider.offset = new Vector2((Mathf.Lerp(1f, laserRange, linearT)) / 2, capsuleCollider.offset.y);

In the above code that you provided this is what happens:

The extra parentheses around the:
Mathf.Lerp(1f, laserRange, linearT)

This makes sure that the Lerp operation is performed before the division of 2

If you removed the extra set of parentheses, the division of 2 would be performed first, and in this context, that isn’t what we want, here is a a unity documentation on this for further explanation:

Hope this helps!

1 Like

Got so focused on this, I forgot 7th grade math for a sec. Thanks @Christopher_Powell !

1 Like

Anytime, glad I could help you out a bit, I happen to be in 9th grade right now, so not far off :wink:

1 Like

This is not quite correct. The extra set of parentheses here is pointless. Mathf.Lerp is not a mathematical construct, so there is nothing the division can do until the lerp has provided a result. The division cannot happen first, because there’s nothing to divide until the lerp has executed.

4 Likes

I didn’t know that, thanks for clearing it up, I guess I got it all twisted :woozy_face:

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms