我有一个精灵,我需要用触摸旋转它,但它位于不同的层。是否有可能更新它的位置?
E.G。 Sprite拥有它自己的图层,但它的位置需要在主游戏中更新
这是我到目前为止所拥有的。
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "GameScene.h"
@interface G : CCLayer {
CCSprite *g;
CGFloat gRotation;
}
@end
------------------------------------------
#import "G.h"
@implementation G
-(id) init
{
if ((self = [super init]))
{
CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
g = [CCSprite spriteWithFile:@"g.png"];
[self addChild:g z:-1];
//[self scheduleUpdate];
if (g.rotation == 360)
{
[self unscheduleUpdate];
}
}
return self;
}
- (void)update:(ccTime)delta
{
g.rotation = gRotation;
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint firstLocation = [touch previousLocationInView:[touch view]];
CGPoint location = [touch locationInView:[touch view]];
CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
CGPoint firstTouchingPoint = [[CCDirector sharedDirector] convertToGL:firstLocation];
CGPoint firstVector = ccpSub(firstTouchingPoint, g.position);
CGFloat firstRotateAngle = -ccpToAngle(firstVector);
CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);
CGPoint vector = ccpSub(touchingPoint, g.position);
CGFloat rotateAngle = -ccpToAngle(vector);
CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);
gRotation += currentTouch - previousTouch;
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}
- (void) dealloc
{
CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
[super dealloc];
}
@end
GameScene
#import "GameScene.h"
#import "MainMenu.h"
#import "G.h"
@implementation GameScene
+(CCScene *) scene
{
CCScene *scene = [CCScene node];
GameScene *layer = [GameScene node];
[scene addChild: layer];
return scene;
}
-(void) tapG: (id) sender
{
G *gView;
gView = [[G alloc] init];
gView.position = ccp(100, 100);
[self.parent addChild:gView z:1001];
[gView schedule:@selector(update:)];
[gView release];
}
-(id) init
{
if ((self = [super init]))
{
tG = [CCMenuItemImage itemFromNormalImage:@"tp.png" selectedImage:@"tp.png" disabledImage:@"tpaperd.png" target:self selector:@selector(tapG:)];
gt = [CCMenu menuWithItems:tG, nil];
gt.position = ccp(210, 80);
[gt alignItemsHorizontallyWithPadding:10];
[self addChild:gt z:0];
}
return self;
}
- (void) dealloc
{
CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
[super dealloc];
}
它会调出精灵,但精灵不会旋转。
答案 0 :(得分:0)
您可以为其他图层安排更新。
你确定你的G图层设置为启用触控吗?分配gView后尝试gView.isTouchEnabled = YES;
。您可能需要确认协议。将<CCStandardTouchDelegate>
添加到您的CCLayer界面:@interface G : CCLayer <CCStandardTouchDelegate> { ....
您也可以使用-(void)update:(ccTime)delta
安排[gView scheduleUpdate];
方法,它会提供相同的结果,但更方便。