#objective-c #drag-and-drop #sprite-kit #sprite #touch-event
#objective-c #перетаскивание #sprite-kit #спрайт #событие касания
Вопрос:
Я пытаюсь создать приложение, которое создает узел спрайта при начале касания, перетаскивает его при движении пальца пользователя и отбрасывает его, когда касание закончилось. То, что у меня есть сейчас, просто создает новый спрайт для каждого нового местоположения касания:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKSpriteNode *gamePiece = [self pickObject];
gamePiece.position = location;
gamePiece.physicsBody.dynamic = NO;
[self addChild:gamePiece];
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKSpriteNode *gamePiece = [self pickObject];
gamePiece.position = location;
gamePiece.physicsBody.dynamic = NO;
[self addChild:gamePiece];
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKSpriteNode *gamePiece = [self pickObject];
gamePiece.position = location;
gamePiece.physicsBody.dynamic = NO;
[self addChild:gamePiece];
}
}
Как мне перенести один и тот же узел спрайта в методы касания? Я повсюду искал учебные пособия, но, похоже, ничто не подходит именно к тому, что мне нужно.
Ответ №1:
Вы можете сделать это, сохранив переменную экземпляра для касания, а также SKSpriteNode, связанную с этим касанием.
@implementation MyScene
{
UITouch *currentTouch;
SKSpriteNode *currentGamePiece;
}
Затем измените делегаты касания следующим образом:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKSpriteNode *gamePiece = [self pickObject];
gamePiece.position = location;
gamePiece.physicsBody.dynamic = NO;
[self addChild:gamePiece];
currentTouch = touch;
currentGamePiece = gamePiece;
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
if ([touch isEqual:currentTouch])
{
currentGamePiece.position = location;
}
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches)
{
CGPoint location = [touch locationInNode:self];
if ([touch isEqual:currentTouch])
{
currentGamePiece.position = location;
currentGamePiece = nil;
currentTouch = nil;
}
}