在touchMoved实现时CCButton无法正常工作

时间:2015-01-20 18:09:16

标签: ios drag-and-drop cocos2d-x ccsprite cocos2d-x-3.0

我必须放置功能,可以将CCButton拖动到适当的位置,无论用户需要放置它们。

我为此创建了一个自定义类,但问题是当用户点击按钮时没有调用按钮的click方法。

touchyButton.h

#import "cocos2d.h"
#import "cocos2d-ui.h"

@interface touchyButton : CCButton { ... }
@property (nonatomic, assign) BOOL touchMoved;
@end

touchyButton.m

#import "touchyButton.h"


@implementation touchyButton

- (void) touchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    NSLog(@"touchMoved...", nil);
    self.touchMoved = YES;
    self.anchorPoint = ccp(0.5, 0.5);
    CGPoint touchLoc = [touch locationInNode:self.parent];
    //CGPoint inTouchLoc = [self convertToNodeSpace:self.anchorPoint];
    //CGPoint touchP = ccpAdd(touchLoc, inTouchLoc);
    //self.position = [self.parent convertToNodeSpace: touchP];
    self.position = touchLoc;
}

- (void) touchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    self.touchMoved = NO;
    NSLog(@"touchEnded...", nil);
}

@end

正如代码所解释的那样,当用户拖动按钮时,我们只是试图在屏幕上移动按钮。

在主代码中调用需要显示的按钮。

        touchyButton *btnRight = [touchyButton buttonWithTitle: @"" spriteFrame:[[CCSprite spriteWithImageNamed: @"arrR.png"] spriteFrame]];
        [btnRight setBackgroundOpacity:0.5f forState: CCControlStateNormal];
        [btnRight setAnchorPoint: ccp(1, 0.5)];
        [btnRight setPosition: ccp(viewS.width - 10.f, viewS.height/2)];
        [self addChild: btnRight];
        [btnRight setTarget:self selector: @selector(performRightJump:)];

现在,当用户点击按钮时,该按钮进入选定状态,但performRightJump永远不会触发。任何人都可以建议任何替代方案如何实现按钮与拖动行为与目标行动工作..?任何暗示也会受到赞赏。

还有一件事是,在当前代码中,我只能将按钮的锚点移动到新的触摸点。知道如何以真实的方式移动按钮吗?当前的方法会导致第一次点击移动,按钮的锚点跳到点击点的问题。

1 个答案:

答案 0 :(得分:1)

此代码为cocos2dx,但对您有用

  

创建一个新的类classA和classB

添加此代码 classA.h

{
//here implement 
 CC_SYNTHESIZE_RETAIN(classB *, _ classB, _ ClassB);
}

classA.cpp

bool classA::init()
{
set_classB(classB::initwithclass());
   this->addChild(get_ClassB(),0);


//here create button
   return true;


}
bool classA:: onTouchBegan (Touch *touch ,Event *event)
{

_classB->setposition(touchLoc); 
  return true;
}
void classA:: onTouchMoved(Touch *touch, Event *event)
{
}
void classA:: onTouchEnded(Touch *touch ,Event *event)
{


}
//as well as this code use in cocos2d