Question

I am making an app in which I want to have some thing happen If an image moves over another point. such as first I have an image moving horizontally across the screen,'

self.ball.center = CGPointMake(self.ball.center.x + self.gravity.x / 8.0 * 200.0, 9);

then when it gets to a certain place another image moves down from that spot.

CGPoint a = CGPointMake(9, 9);
if (CGPointEqualToPoint(ball.center,a)) {

                balla.hidden = NO;
                self.balla.center = CGPointMake(self.balla.center.x , (self.balla.center.y)- (self.gravity.y / 8.0 * 200.0));
            }

the first time it works ok but when I put in the next statement to move another image down from another spot nothing happens.

CGPoint b = CGPointMake(86, 9);
            if (CGPointEqualToPoint(ball.center,b)) {

                ball2a.hidden = NO;
                self.ball2a.center = CGPointMake(self.ball2a.center.x , (self.ball2a.center.y)- (self.gravity.y / 8.0 * 200.0));}

Any ideas as to why this isn't working

Was it helpful?

Solution

If you're moving the ball by adding some floating-point value offset, you might be "skipping over" the point b - you may never hit b, but rather appear slightly before it and then slightly after it.

Rather than testing if you're "equal" to the point, you could be better off comparing the distance between the ball and the point and seeing if it is inside some small radius. A simple euclidean distance could work.

CGFloat euclid_dist(CGPoint a, CGPoint b)
{
    return sqrt((b.x-a.x)*(b.x-a.x) + (b.y-a.y)*(b.y-a.y));
}

You could then use this to see if you've "hit" the point:

if (euclid_dist(ball.center, b) < 0.1)
{
    // React appropriately
}

In general it's problematic to test for equality between floating point numbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top