0
votes

I'm trying to tap a falling object in my Cocos2d/Box2d app.

Here's my touchesBegan code:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *myTouch = [touches anyObject];
    CGPoint location = [myTouch locationInView:[myTouch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
    b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);

    for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()) {
        b2Vec2 bPos = b->GetPosition();
        for (b2Fixture *f = b->GetFixtureList(); f; f=f->GetNext()) {

            if (f->TestPoint(locationWorld)) {
                NSLog(@"hit it!");
            }

        }
    }

I have 2 objects in my world, the ground and the falling object. I have gravity really slow so touching it shoudn't be a problem. What is odd is that my positions seem off by a lot!

In the last run locationWorld (where I tapped) was:

Printing description of locationWorld:
(b2Vec2) locationWorld = {
  x = 7.90625
  y = 9.875
}

I went through the outer loop twice, once for each body, and got:

Printing description of bPos:
(b2Vec2) bPos = {
  x = 3.03125
  y = 19.6643
}
Printing description of bPos:
(b2Vec2) bPos = {
  x = 8.59375
  y = 17.4969
}

What is odd is that the 2nd body, the one reported at (8.59, 17.49) should be the falling object, but the Y coordinate is way off.

This is my first cocos2d/box2d app so I'm sure I'm missing something obvious. I've been googling for awhile and this seems like it should work.

Thanks for any help.

SEE MY ANSWER BELOW, MY CODE HERE IS CORRECT, I'M SETTING UP MY FIXTURES INCORRECTLY.

1
"Touching my fixture fails" <= you sure this is the type of question you want to ask on stackoverflow.com? Made my day! :DLearnCocos2D
and your comment made me smile after a very hard day! I'm going to need that tomorrow when I tackle this again. I have the touches working but my world is getting corrupted. Don't have enough info for an answer...Paul Cezanne
Still laughing here … :DLearnCocos2D

1 Answers

0
votes

ok, this is sorta working now but I'm sure I'll have another question from it.

When I ran this above I had created a fairly small dynamic box so the items would pile up on the ground, overlapping each other.

dynamicBox.SetAsBox(.25f, .25f)

This was the cause. When I open this up to something much larger, say:

dynamicBox.SetAsBox((spriteSize.width/PTM_RATIO)/4, (spriteSize.height/PTM_RATIO)/4);

Then it becomes possible with the above code to touch a body. (So my question needs to be remformulated since I do want the objects piling up, overlapping each other.

I also have no idea why I needed to divide the size by 4 to get the items close to each other, that's just plain bothering me.