【问题标题】:Pressed button in SpriteKitSpriteKit中的按下按钮
【发布时间】:2016-01-17 21:33:52
【问题描述】:

我找到一些代码可以帮助我创建一个按钮,当它按下时可以动画。但它在objective-c上。一般来说,我可以理解这段代码是什么,但我无法快速正确地翻译它。请帮我快速翻译一下。非常感谢。

1.

- (SKSpriteNode *)fireButtonNode
{
    SKSpriteNode *fireNode = [SKSpriteNode spriteNodeWithImageNamed:@"fireButton.png"];
    fireNode.position = CGPointMake(fireButtonX,fireButtonY);
    fireNode.name = @"fireButtonNode";
    fireNode.zPosition = 1.0;
    return fireNode;
}

2.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];

if ([node.name isEqualToString:@"fireButtonNode"]) {
    }
}

【问题讨论】:

  • @Mr.Tigr 哦,我大体上同意 IInspectable 所说的话。我为你做了一个例子,因为它不需要太多时间,特别是因为我注意到你是一个新成员,但最好包括你迄今为止尝试过的东西来展示解决问题的努力问题。这样,您就不会面临被否决的风险。

标签: ios swift sprite-kit


【解决方案1】:

在斯威夫特中:

func getFireButtonNode()->SKSpriteNode{

        let fireButtonX = CGRectGetMidX(frame), fireButtonY = CGRectGetMidY(frame)

        let fireNode = SKSpriteNode(imageNamed: "fireButton")
        fireNode.position = CGPoint(x: fireButtonX, y: fireButtonY)
        fireNode.name = "fireButtonNode"
        fireNode.zPosition = 1.0

        return fireNode

    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        if let touch = touches.first {


            let location = touch.locationInNode(self)

            let node = nodeAtPoint(location )

            if node.name == "fireButtonNode" {
                //do your stuff here
            }
        }

    }

请注意,变量 fireButtonXfireButtonY 在您的代码示例中永远不会被初始化。您可以像我一样在getFireButtonNode 中定义它们,也可以在调用getFireButtonNode 方法时将它们作为参数传递,如下所示:

 func getFireButtonNode(xPos:CGFloat, _ yPos:CGFloat)->SKSpriteNode{}

然后这样称呼它:

getFireButtonNode(100,100)

如果你想这样称呼它:

getFireButtonNode(xPos:100, yPos:100)

您必须明确定义外部和本地参数名称,如下所示:

func getFireButtonNode(xPos x:CGFloat, yPos y:CGFloat)->SKSpriteNode{}

其中 xPos(以及 yPos)是一个外部参数名称,当您调用该函数时,它将用作参数名称。 x 和 y 是局部参数,你可以在函数体内部使用它们。

【讨论】:

    【解决方案2】:

    您看过苹果的演示项目“DemoBots”吗?他们有一个按钮助手。

    https://developer.apple.com/library/ios/samplecode/DemoBots/Listings/DemoBots_Nodes_ButtonNode_swift.html#//apple_ref/doc/uid/TP40015179-DemoBots_Nodes_ButtonNode_swift-DontLinkElementID_62

    另一个更简单的例子

    http://nathandemick.com/programming/tutorial/2014/09/23/buttons-sprite-kit-using-swift.html

    最后是一个 gitHub 项目。

    https://github.com/nguyenpham/sgbutton

    在我的个人游戏中,我使用了带有一些与我相关的调整的苹果演示机器人示例。这个类也有助于 tvO 关注的东西。

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多