objective c - What is the difference between == and <= in this case -


i working on making game, , wondering why construct == operator doesn't work while lower 1 does. used nslog message afterwards test.

    if (pipe.position.x == bird.position.x){ no idea why doesn't work     if ((pipe.position.x <= bird.position.x) & (pipe.position.x > bird.position.x - 1)){ 

this because 1 (or both) of position.x's floating-point2 value non-zero difference1 between 2 position values such second condition true.

since p <= b true values make p == b true, see why works "unexpectedly" let's choose values such expression p == b false2 yet p < b true , p > b - 1 true.

given p = 3.2 (pipe) , b = 3.7 (bird), example, then

   p == b -> 3.2 == 3.7 -> false 

but

   (p <= b) & (p > b - 1) -> (3.2 <= 3.7) & (3.2 > 3.7 - 1) -> (3.2 <= 3.7) & (3.2 > 2.7) -> true & true -> true 

instead, detect when bird "is crossing" pipe, assuming x increases right, consider

   // bird's head "right" of pipe leading edge..    bird_x >= pipe_x    // ..but bird's butt not "right" of pipe trailing edge.    // (also note use of &&, logical-and operator) && (bird_x - bird_width <= pipe_x + pipe_width) 

of course, using non-rectangle (or forgiving overlap) collision detection lead less frustrating flapping!


1 issue occurs because there particular floating-point values (but there no integer values) can cause observed effect.

first, reiterate assumption p not equal b, given first condition not succeed. let's suppose p <= b written p == b || p < b since p == b false , can write p < b tautology.

since both clauses in second condition true (such true && true -> true), have rules: 1) p < b true, , 2) p > b - 1 true.

rewriting p < b p - b < 0 , p > b - 1 p - b > -1, , replacing p - b x yields: x < 0 , x > -1. however, there no integer value of x satisfies -1 < x < 0.

(in first section, p = 3.2 , b = 3.7, x = (p - b) = 0.5 satisfies given constraints when x not restricted integer value.)


2 above aside, it possible p , b "very close different" floating-point values such there non-zero difference between them - due rounding, may displayed same integer value! see how dangerous compare floating point values? , related questions cause , "odd" behavior of such when using ==.

if case round integer values , use integer comparison, or; rely entirely on relational comparison such shown in proposed condition, or; use epsilon comparison "nearly equal" of floating-point values.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -