How to get sprites react to touches in cocos2d android?

别等时光非礼了梦想. 提交于 2019-12-10 14:43:44

问题


i have 1 gun when tap on any point on the screen bullets fires out, but according to my requirement there are 3 guns(sprites) when touched on any of the sprites bullets must fire up, when googled i came to know that this can be done by using targetedTouchDelegate or to loop all the spirites and set flag for each touched sprite, i have seen the code for this in iphone, but could not find for android, please can anybody tell how to use do this in android? or any links or books for cocos2d-android would be useful not only for me to others also. Thanks,


回答1:


Well what I would do in such a case would be get the rect for my sprite using this

CGRect projectileRect = CGRect
                .make(sprite.getPosition().x
                        - (sprite.getContentSize().width / 2.0f),
                        sprite.getPosition().y
                                - (sprite.getContentSize().height / 2.0f),
                        sprite.getContentSize().width,
                        sprite.getContentSize().height);

and I will detect if the clicked point is in the rectangle of that particular sprite you can override onccTouchBegan to get the clicked point and then look for the collision

@Override
public boolean ccTouchesBegan(MotionEvent event) {
    // TODO Auto-generated method stub

    CGPoint touchLocation=CGPoint.ccp(event.getX(), event.getY());
    CGRect targetRect = CGRect.make(
            event.getX(),
            event.getY(),
            5,
            5);

        if (CGRect.intersects(projectileRect, targetRect))
                  1st sprite is clicked 

    return super.ccTouchesBegan(event);

}

This is my work around.



来源:https://stackoverflow.com/questions/16648196/how-to-get-sprites-react-to-touches-in-cocos2d-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!