【问题标题】:cocos2d ccTouchesMoved moving sprite only to top right cornercocos2d ccTouchesMoved 仅将精灵移动到右上角
【发布时间】:2011-06-09 15:27:00
【问题描述】:

请原谅我的基本问题,因为我对 cocos2d 还很陌生,但是我在移动精灵时遇到了问题。该方法似乎可以满足我的要求……只要它沿正 x 和正 y 方向(右上角)移动。如果我尝试将其向下或向左移动,则不起作用。

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *myTouch = [touches anyObject];
    CGPoint point = [myTouch locationInView:[myTouch view]];
    point = [[CCDirector sharedDirector] convertToGL:point]; //create point location
    CCNode *sprite = [self getChildByTag:kTagSprite]; //set sprite
    CGRect spriteRect = CGRectMake(sprite.position.x, sprite.position.y, sprite.contentSize.width, sprite.contentSize.height); //create box around sprite and get position
    if(CGRectContainsPoint(spriteRect, point)){
        [sprite setPosition:point];  //if my pointer is inside of the sprite box, move the sprite
    }
}

谢谢。

编辑:添加我的初始化和标记参考

-(id) init{
    if((self = [super init])){
        self.isTouchEnabled = YES;
        CCSprite *mySprite = [CCSprite spriteWithFile:@"sprite.png"];
        mySprite.position = ccp(240, 40);
        [self addChild:mySprite z:0 tag:kTagSprite];
    }
    return self;
}

我在以下位置声明了 kTagSprite:

enum{
    kTagSprite
};

【问题讨论】:

  • 你是如何在 kTagSprite 后面创建对象的?向我们展示代码..如何在 init 中加载精灵?
  • 问题已编辑。感谢收看。

标签: cocos2d-iphone touch cgrect


【解决方案1】:
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *myTouch = [touches anyObject];
    CGPoint point = [myTouch locationInView:[myTouch view]];
    point = [[CCDirector sharedDirector] convertToGL:point]; //create point location
    CCSprite *sprite = [self getChildByTag:kTagSprite]; //set sprite

    if(CGRectContainsPoint([sprite boundingBox], point)){
        [sprite setPosition:point];  //if my pointer is inside of the sprite box, move the sprite      CCLOG(@"THIS WILL BE CALLED");
    }
}

运行代码并查看控制台,看看是否会调用日志..

【讨论】:

  • 至于您建议的顶部,控制台仅在对象向上或向右移动或两者混合时才达到该 if 语句。单击对象或将其向下和/或向左移动,它没有到达 if 语句内。但是,使用您的第二个代码块,一切正常!非常感谢你。我不知道那个 boundingBox 选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
相关资源
最近更新 更多