gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:10:18 24 4
gpt4 key购买 nike

我正在构建一个无限横向滚动游戏,我需要在其中画一条线,让球可以在其中移动。我最初实现这条线的系统是在触摸移动的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com