在Spritekit中创建raycast

在Spritekit中创建raycast

本文介绍了在Spritekit中创建raycast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spritekit构建游戏,并试图构建将玩家与玩家点击的点连接起来的光线投射.这就像一条绳子,将玩家连接到他或她所点击的位置.例如,如果玩家在x:0,y:0点处轻击,则它将变成将两者相互连接的绳索.随着时间的流逝,绳索将变短,玩家将被拉向绳索.玩家确实有一个物理体.当演奏者松开手指时,绳索将被移开,并且演奏者将不再被拖动到该点.

I am building a game using Spritekit and am trying to build a raycast that will connect the player with the point where the player tapped. It will be like a rope that connects the player to the point where he or she tapped. For example if a player taps at the point x: 0, y: 0 then it will become a rope that connects both things with each other. With the time the rope will become shorter and the player will be dragged against it. The player does have a physicsbody. When the player releases the finger the rope will be remove and the player are not going to be dragged to that point anymore.

我想存档的内容与您使用spritekit统一搜索raycast一样.

I want to archive the same thing as if you search raycast in unity but with spritekit.

我知道如何实现触摸功能以及何时释放触摸.所以问题是我如何如所描述的那样进行射线广播.我还希望具有某种视觉效果,这意味着一个skshapenode或可以指示玩家前进方向的东西.

I know how to implement the touch function as well as when he or she releases a touch. So the question is how do I make a raycast as described. I would also like to have some sort of visual effect which means a skshapenode or something that indicates where the player is going.

曾经尝试使用SkPhysicsJoints,但是我没有成功.

Have tried using SkPhysicsJoints but I'm not successful.

任何帮助将不胜感激!

推荐答案

场景中的 physicsWorld 对象使用

func enumerateBodies(alongRayStart start: CGPoint, end: CGPoint, using block: @escaping (SKPhysicsBody, CGPoint, CGVector, UnsafeMutablePointer<ObjCBool>) -> Void)

您可以这样使用:

self.physicsWorld.enumerateBodies(alongRayStart: playerPosition, end: clickPosition) { body, point, vector, object in
    if let node = body.node as? SKSpriteNode {
        node.color = SKColor.red.withAlphaComponent(0.2)
        let pointNode = SKSpriteNode(color: .cyan, size: CGSize(width: 5, height: 5))
        pointNode.position = point
        let path = CGMutablePath()
        path.move(to: playerPosition)
        path.addLine(to: clickPosition)
        path.closeSubpath()
        let line = SKShapeNode(path: path)
        line.strokeColor = .green
        line.fillColor = .green
        self.addChild(line)
        self.addChild(pointNode)
    }
}

并在每次点击时获得此结果:

And get this result on each click:

完整示例在这里: https://github.com/Maetschl/SpriteKitExamples/blob/master/Raycast2dLinesVsObjects/Raycast2dLinesVsObjects/GameScene.swift

这篇关于在Spritekit中创建raycast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 13:11