Create a raycast in spritekit

一个人想着一个人 提交于 2021-02-18 19:29:30

问题


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.

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

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.

Have tried using SkPhysicsJoints but I'm not successful.

Any help would be appreciated!


回答1:


Raycast is supported by physicsWorld object on your scene, with the method

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

You can use like this:

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:

The complete example it's here: https://github.com/Maetschl/SpriteKitExamples/blob/master/Raycast2dLinesVsObjects/Raycast2dLinesVsObjects/GameScene.swift



来源:https://stackoverflow.com/questions/60137122/create-a-raycast-in-spritekit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!