【问题标题】:Spritekit and Touch event (Coordinates seems flipped)Spritekit 和 Touch 事件(坐标似乎翻转了)
【发布时间】:2013-10-03 12:27:27
【问题描述】:

我使用以下代码在 SKScene 上添加了一张图片 -

char1 = [[SKSpriteNode alloc] initWithImageNamed:@"CH_designb_nerd.png"];
    char1.position = CGPointMake(225.0, 65.0);
    char1.anchorPoint = CGPointMake(0, 0);
    [char1 setScale:0.35];
    [self addChild:char1];

然后我试图在图像上创建一个触摸事件,但图像的 CGRect 似乎在屏幕的另一侧完全翻转。我使用了以下代码

(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:self.view];
    if (CGRectContainsPoint(char1.frame, location)) {
        NSLog(@"yaaa!!");

    }
    else{
        NSLog(@"%.2f",location.x);
        NSLog(@"%.2f",char1.position.x);

    }

}

我完全迷失了这一点,因为图像放置得很完美,但坐标或 CGRect 似乎翻转了。图像放置在底部,但只有当我触摸屏幕顶部时,它才会说发生了触摸。

【问题讨论】:

  • 我正在经历完全相同的事情,除了在 swift 中,我认为这与尝试在 SKScene 中使用 touch.locationInView(view) 有关。

标签: objective-c cocoa-touch ios7 sprite-kit


【解决方案1】:

我想这是由于点击位置错误。相反,我会考虑使用SKNode 等效项进行命中测试。像这样的:

UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKSpriteNode *char1 = (SKSpriteNode *)[self childNodeWithName:@"char1Name"];
if ([char1 containsPoint:location])
{
    ...
}

这里可能有一些语法错误,从记忆中输入,但你明白了要点。注意:您需要为char1 设置name 属性来执行查找,或者如果只有该节点,您可以只枚举self.children

【讨论】:

  • 对@Matt 的代码稍作改动:SKNode *node = [self nodeAtPoint:location]; if ([node.name isEqualToString:@"char1Name"]) { ... }
【解决方案2】:

试试这个。

UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];

spriteKit 的好例子Link

【讨论】:

  • 天啊...非常感谢..该死的,这是一个很棒的网站,拥有非常棒的用户..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多