我正在构建一个无限的侧滚动游戏,我需要绘制一条球可以移动的线。我实现该系列的原始系统是在触摸移动的SKSpriteNode中产生的。由于性能原因,这是不成功的。然后我尝试使用CGPath和SKShapeNode,但它的性能极差,并且没有想法。基本上,我需要在玩家滑动或绘制的地方创建一条路径,我需要一个物理主体来完全包围所绘制线条的笔划。为了节省性能,移除不在相机视野中的行程或路径点也是非常重要的。我的目标的说明如下。
答案 0 :(得分:2)
以下是如何使其有效运作的示例。您可以研究如何在场景中打开和关闭它以获得更高的效率。
基本前提是您使用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
}
}