Garry's Mod Wiki

Revision Difference

Vector:DistToSqr#529302

<function name="DistToSqr" parent="Vector" type="classfunc"> <description>Returns the squared distance of 2 vectors, this is faster than <page>Vector:Distance</page> as calculating the square root is an expensive process. <note>Squared distances should not be summed. If you need to sum distances, use <page>Vector:Distance</page>.</note>⤶ <note>When peforming a distance check, ensure the distance being checked against is squared. See example code below.</note> </description> <note>Squared distances should not be summed. If you need to sum distances, use <page>Vector:Distance</page>.⤶ When performing a distance check, ensure the distance being checked against is squared. See example code below.</note> </description> <realm>Shared</realm> <args> <arg name="otherVec" type="Vector">The vector to calculate the distance to.</arg> </args> <rets> <ret name="" type="number">Squared distance to the vector</ret>⤶ <ret name="" type="number">Squared distance to the vector.</ret>⤶ </rets> </function> <example> <description>Checks if a player is within `dist` units of another player in the most efficient way possible.</description> <code> function PlayerWithinBounds(ply, otherPly, dist) function PlayerWithinBounds( ply, target, dist ) -- Square the input distance in order to perform our distance check on Source units. local distsqr = dist * dist return ply:GetPos():DistToSqr(otherPly:GetPos()) < distsqr⤶ local distSqr = dist * dist return ply:GetPos():DistToSqr( target:GetPos() ) < distSqr⤶ end print(PlayerWithinBounds(Entity(1), Entity(2), 500)) print( PlayerWithinBounds( Entity(1), Entity(2), 500 ) ) </code> <output>true</output>⤶ ⤶ </example> <output>⤶ ```⤶ true⤶ ```⤶ </output>⤶ </example>