简体   繁体   English

将 SKSpritenode 向一个方向展开,在 Xcode SpriteKit 中,使用 Swift

[英]Expand SKSpritenode in one direction, in Xcode SpriteKit, using Swift

I want to make an SKSpritenode expand only in one direction, in this case only upwards.我想让SKSpritenode只在一个方向上扩展,在这种情况下只向上扩展。

override func didMoveToView(view: SKView) {
    var rightlegs = SKSpriteNode()
    rightlegs.size = CGSize(width: 10, height: 50)
    rightlegs.color = SKColor.yellowColor()
    rightlegs.position = CGPointMake(self.frame.width / 2 + 20, self.frame.height / 2 - 40)
    self.addChild(rightlegs)


}

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   /* Called when a touch begins */

So.. When i press the screen I want the height to expand;所以..当我按下屏幕时,我希望高度扩展; however, not from both direction.然而,不是从两个方向。 How do I solve this problem?我该如何解决这个问题? Thank for your time:)感谢您的时间:)

You can do it by changing the anchorPoint property of the sprite to CGPoint(x:0.5, y:0.0) (this will bottom-align sprite's texture) and scaling the sprite's height using yScale property, like this:您可以通过将精灵的anchorPoint属性更改为CGPoint(x:0.5, y:0.0) (这将底部对齐精灵的纹理)并使用yScale属性缩放精灵的高度来实现,如下所示:

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

    let rightlegs = SKSpriteNode(color: .yellowColor(), size: CGSize(width: 10, height: 50))

    override func didMoveToView(view: SKView) {

        rightlegs.anchorPoint.y = 0.0

        rightlegs.position = CGPointMake(self.frame.width / 2 + 20, self.frame.height / 2 - 40)
        self.addChild(rightlegs)    
    }

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

        //Without animation
        rightlegs.yScale += 0.2
    }
}

Or you can make it animated using some of the SKAction scaling methods:或者您可以使用一些 SKAction 缩放方法使其动画化:

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

   //With animation

   rightlegs.runAction(SKAction.scaleYTo(rightlegs.yScale + 0.2, duration: 0.2))
}

About anchorPoint from docs:关于文档中的anchorPoint

Defines the point in the sprite that corresponds to the node's position.定义精灵中对应于节点位置的点。

You specify the value for this property in the unit coordinate space.您可以在单位坐标空间中指定此属性的值。 The default value is (0.5,0.5), which means that the sprite is centered on its position.默认值为 (0.5,0.5),表示精灵以其位置为中心。

Basically what anchorPoint does is that it defines how texture will be drawn relative to node's position and affects on rotation and scaling of a node...基本上, anchorPoint作用是定义如何相对于节点的位置绘制纹理并影响节点的旋转和缩放......

A good explanation about how anchor point works and what it does can be found in Apple's Working with Sprites section of documentation.关于锚点的工作原理及其作用的一个很好的解释可以在 Apple 文档的Working with Sprites部分找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM