swift - 具有物理和强大性能的用户创建线的创建方法

标签 swift sprite-kit

我正在构建一个无限横向滚动游戏,我需要在其中画一条线,让球可以在其中移动。我最初实现这条线的系统是在触摸移动的 SKSpriteNode 中生成。由于性能原因,这没有成功。然后我尝试使用 CGPath 和 SKShapeNode,但它的性能极差并且我没有想法。基本上,我需要在玩家滑动或绘制的地方创建一条路径,我需要一个物理体来完全包围所绘制线条的笔划。删除不再在相机视野中的路径的笔划或点以节省性能也非常重要。下面是我的目标说明。

Illustration of goal

最佳答案

这是一个如何让它高效工作的例子。您可以研究如何在场景中启用和禁用它以提高效率。

基本前提是您使用 1 个 SKShapeNode 来绘制您的连续线。绘制完线条后,将其转换为纹理以用作 SKSpriteNode

//
//  GameScene.swift
//  physics
//
//  Created by Anthony Randazzo on 7/28/17.
//  Copyright © 2017 SychoGaming. All rights reserved.
//

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    private var shape = SKShapeNode()
    private var path : CGMutablePath!

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

        let position =  touches.first!.positionOnScene
        path = CGMutablePath()
        path.move(to: CGPoint.zero)
        shape.path = path
        shape.position = position
        self.addChild(shape)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let position =  touches.first!.positionOnScene - shape.position
        path.addLine(to: position)
        shape.path = path
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let position =  touches.first!.positionOnScene - shape.position
        path.closeSubpath()
        shape.removeFromParent()
        autoreleasepool
        {

            let sprite = SKSpriteNode(texture: self.view?.texture(from: shape,crop:shape.frame))

            sprite.position = CGPoint(x:shape.frame.midX,y:shape.frame.midY)
            let physicsBody = SKPhysicsBody(polygonFrom: path)
            physicsBody.isDynamic = false
            sprite.physicsBody = physicsBody

            addChild(sprite)
        }
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        let position =  touches.first!.positionOnScene
    }


    override func update(_ currentTime: TimeInterval) {
    }
}

extension UITouch
{
    var positionOnScene : CGPoint
    {
        return self.location(in: (self.view as! SKView).scene!)
    }
}
extension CGPoint
{
    static public func -(lhs:CGPoint,rhs:CGPoint) -> CGPoint
    {
        return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
    }
    static public func -= (lhs:inout CGPoint,rhs:CGPoint)
    {
        lhs = lhs - rhs
    }
}

关于swift - 具有物理和强大性能的用户创建线的创建方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45366755/

相关文章:

swift - 在 Swift 中循环播放 A 到 B 的动画

ios - 如何在显示查看激励应用程序的选项之前检查互联网连接?

Swift Struct with Lazy,符合协议(protocol)的私有(private)属性(property)

c - 在 Swift 中使用 OpenSSL stack_st_x509?

xcode 6 beta 6 sort() 似乎不像 Swift 文档所说的那样工作

swift - (swift/xcode) 错误消息 : 'Setting this node as parent would create a loop'

ios - 每 n 天安排一次本地通知(时区安全)

ios - 如何使用 cocoa pod 的 Storyboard引用?

ios - arc4random 函数随机执行两次或三次

swift - SKSpriteNode 导致场景变灰