我创建了一个名为的节点,并对其进行了修改,以使其在触摸并拖动该节点时从屏幕上拖动。由于某种原因,这种方法(下面的代码)使我可以将屏幕上的任何节点悬停。我如何才能仅使一个“ testNode2”生效。
另外,我是否可以将节点拖动到手指的移动上,但是如果手指在屏幕上的任何地方触摸,而不仅仅是在节点本身被触摸时,这都可以工作?(但不要跳到手指的位置,只需根据手指的移动来移动)。例如,在任何地方按下屏幕,然后向左拖动100像素,则节点将向左移动100像素。
我的代码如下
-(void) colourSprite2:(CGSize)size {
self.testNode2 = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:CGSizeMake(30, 30)];
self.testNode2.position = CGPointMake(self.size.width/2, self.size.height/1.1);
self.testNode2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.testNode2.frame.size];
[self addChild:self.testNode2];
}
-(void)touchesBegan:(NSSet*) touches withEvent:(UIEvent*) event
{ self.testNode2 = [self nodeAtPoint:[[touches anyObject] locationInNode:self]]; }
-(void)touchesMoved:(NSSet*) touches withEvent:(UIEvent*) event
{ self.testNode2.position = [[touches anyObject] locationInNode:self]; }
-(void)touchesEnded:(NSSet*) touches withEvent:(UIEvent*) event
{ self.testNode2 = nil; }
触摸委托返回一个NSSet
触摸,其中包含多个UITouch对象,每个对象都与与实现委托方法的对象相关的触摸相对应。
在您的情况下,该节点会将自己移动到委托遇到的任何触摸的位置。这包括在屏幕上的多次触摸。
您应该阅读有关UITouch和UIResponder类的信息。
解决您的问题的方法将是跟踪用于移动节点的特定触摸。
维护一个UITouch对象作为实例变量:
@implementation MyScene
{
UITouch *currentTouch;
}
然后,按以下方式跟踪特定的触摸:
-(void)touchesBegan:(NSSet*) touches withEvent:(UIEvent*) event
{
UITouch *touch = [touches anyObject];
SKNode *node = [self nodeAtPoint:[touch locationInNode:self]];
if (currentTouch == nil && [node isEqual:self.testNode2])
{
currentTouch = touch;
}
}
-(void)touchesMoved:(NSSet*) touches withEvent:(UIEvent*) event
{
UITouch *touch = [touches anyObject];
if ([touch isEqual:currentTouch])
{
self.testNode2.position = [touch locationInNode:self];
}
}
-(void)touchesEnded:(NSSet*) touches withEvent:(UIEvent*) event
{
UITouch *touch = [touches anyObject];
if ([touch isEqual:currentTouch])
{
self.testNode2 = nil;
currentTouch = nil;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句