我正在开发一款SpriteKit游戏。 现在我在MyScene.m中创建了一个控制杆,它控制在我的MyScene.m中创建的精灵。 但是我试图将MyScene.m中的精灵移到自己的类中。 但是当我这样做时,我的操纵杆就再也无法移动了。这是Player.m中的代码 和MyScene.m中的操纵杆代码(我导入了Player.h,但我仍然无法移动玩家精灵)。 谢谢。
#import "Player.h"
#import "MyScene.h"
@implementation Player
- (instancetype)init {
SKTextureAtlas *atlas =
[SKTextureAtlas atlasNamed: @"characters"];
SKTexture *texture = [atlas textureNamed:@"walk1"]; texture.filteringMode = SKTextureFilteringNearest;
if (self = [super initWithTexture:texture])
{ self.name = @"players";
CGFloat minDiam = MIN(self.size.width, self.size.height); minDiam = MAX(minDiam-16, 4);
self.physicsBody =
[SKPhysicsBody bodyWithCircleOfRadius:minDiam/2.0];
self.physicsBody.usesPreciseCollisionDetection = YES;
self.physicsBody.allowsRotation = NO;
self.physicsBody.restitution = 1;
self.physicsBody.friction = 0;
self.physicsBody.linearDamping = 0;
}
return self;
}
@end
在MyScene.m中,更新方法是:
-(void)update:(NSTimeInterval)currentTime {
if (button) {
SKNode *controlNode = [self childNodeWithName:@"controlPadNode"];
SKNode *node = [self childNodeWithName:@"Players"];
float angle = atan2f (touchY - Y, touchX - ) ;
SKAction *moveShip=[SKAction moveByX:6*cosf(angle) y:0 duration:0.005];
[node runAction: moveShip];
}
}
我已添加此代码
Player *playerNode=[[Player alloc]init];
playerNode.name=@"Players";
[self addChild:playerNode];
到我的myscene self init.However操纵杆仍然不移动这个精灵,只有我在MyScene.m中构建的精灵
答案 0 :(得分:1)
您可以向操作员类添加对操纵杆的弱引用,当您将玩家添加到场景时,将操纵杆传递给对象(在MyScene.m中):
Player *playerNode=[[Player alloc]init];
playerNode.name=@"Players";
playerNode.joystic= self.myJoystic;
[self addChild:playerNode];
之后在Player类的update方法中,只需检查操纵杆状态:
if (self.joystic.leftbuttonpressed)
{
//Left button pressed
}
else if (rightbuttonpressed)
//...
你可以这样做。您也可以使用委托,这取决于哪种方式更适合您。