gpt4 book ai didi

ios - 试图制作我可以从下面跳过去但落在上面的平台。无法微调逻辑

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:36:53 26 4
gpt4 key购买 nike

我的目标是在 .sks 文件中设置我的所有平台,以便更轻松地设计我的关卡。


这是在 didMove 之前在 game scene.swift 的顶部声明的:

private var JumpThroughPlatformObject = SKSpriteNode()

这是在 DidMove 中:

if let JumpThroughPlatformObjectNode = self.childNode(withName: "//jumpThroughPlatform1") as? SKSpriteNode {
JumpThroughPlatformObject = JumpThroughPlatformObjectNode}

我引用平台以从 .sks 获取它的高度,因为我的所有平台都将具有相同的高度,我只需要从一个平台获取它。

下面是我试图在我的更新方法中使用的方法来关闭碰撞,直到我的播放器完全位于平台上方。仅检查我的玩家速度是否大于零的主要问题是:玩家是否处于跳跃的峰值(他的速度减慢至零)。如果发生这种情况并且玩家在平台内,他要么立即弹到平台顶部,要么向下发射。

我不希望我的平台必须是 1 像素高的线。我还需要让玩家有一个完整的碰撞盒,因为他将与其他类型的环境进行交互。这让我相信我需要以某种方式只将平台顶部注册为碰撞盒,而不是整个平台。

我写的这个 if 语句应该采用平台的 y 位置并将其高度的一半添加到它,因为 y 位置基于 Sprite 的中心我认为这会将平台的碰撞放在它的顶部边界。

我为播放器做了同样的事情,但相反。将玩家碰撞仅放在边界的底部。但它不能完美地工作,我现在不确定为什么。

if (JumpThroughPlatformObject.position.y + (JumpThroughPlatformObject.size.height / 2)) > (player.position.y - (player.size.height / 2))

下面的函数给我带来了 3 个主要问题:

  1. 我的玩家跳跃总是 dy = 80。如果我跳到那个 position.y = 90 的平台,玩家的跳跃峰值会停在平台中间,但他会传送到而不是继续掉到地上。

  2. 如果我掉落,平台的左右边缘仍然会与玩家完全碰撞

  3. 如果我的播放器在一个平台上,而我的正上方有另一个播放器,则播放器无法跳过它。

    设零:CGFloat = 0

        if let body = player.physicsBody {
    let dy = player.physicsBody?.velocity.dy

    // when I jump dy is greater than zero else I'm falling

    if (dy! >= zero) {

    if (JumpThroughPlatformObject.position.y + (JumpThroughPlatformObject.size.height / 2)) > (player.position.y - (player.size.height / 2)) {

    print(" platform y: \(JumpThroughPlatformObject.position.y)")
    print ("player position: \(player.position.y)")

    // Prevent collisions if the hero is jumping
    body.collisionBitMask = CollisionTypes.saw.rawValue | CollisionTypes.ground.rawValue

    }

    }
    else {
    // Allow collisions if the hero is falling
    body.collisionBitMask = CollisionTypes.platform.rawValue | CollisionTypes.ground.rawValue | CollisionTypes.saw.rawValue
    }
    }

如有任何建议,我们将不胜感激。这几天我一直在扯头发。

在 didBegin 和 didEnd 中编辑:

   func didBegin(_ contact: SKPhysicsContact) {

if let body = player.physicsBody {
let dy = player.physicsBody?.velocity.dy
let platform = JumpThroughPlatformObject
let zero:CGFloat = 0


if contact.bodyA.node == player {
// playerCollided(with: contact.bodyB.node!)

if (dy! > zero || body.node!.intersects(platform)) && ((body.node?.position.y)! - player.size.height / 2 < platform.position.y + platform.size.height / 2) {

body.collisionBitMask &= ~CollisionTypes.platform.rawValue

}



} else if contact.bodyB.node == player {
// playerCollided(with: contact.bodyA.node!)
isPlayerOnGround = true

if (dy! > zero || body.node!.intersects(platform)) && ((body.node?.position.y)! - player.size.height / 2 < platform.position.y + platform.size.height / 2) {

body.collisionBitMask &= ~CollisionTypes.platform.rawValue}
}
}
}

func didEnd(_ contact: SKPhysicsContact) {

if let body = player.physicsBody {
// let dy = player.physicsBody?.velocity.dy
// let platform = JumpThroughPlatformObject

if contact.bodyA.node == player {


body.collisionBitMask |= CollisionTypes.platform.rawValue

}else if contact.bodyB.node == player {

body.collisionBitMask |= CollisionTypes.platform.rawValue

}
}
}

添加我所做的,玩家不能再跳过平台。

最佳答案

这是我为 macOS 和 iOS 目标制作的项目的链接:
https://github.com/fluidityt/JumpUnderPlatform

基本上,这一切都与

有关
  1. 检测平台碰撞
  2. 然后判断你的播放器是否在平台下
  3. 让您的玩家通过平台(然后登陆)

--

SK Physics 让这有点复杂:

  1. 在碰撞检测中,您的玩家的 .position.y.velocity.dy引用满足上面的 #2 检查(意味着 #3 永远不会发生),可能已经更改为“假”状态。此外,您的播放器会在第一次接触时从平台弹开。

  2. 没有“自动”方式来确定您的玩家何时完成穿过物体(从而允许玩家降落在平台上)

--

因此,为了让一切正常运行,必须发挥一点创造力和独创性!


1:平台碰撞检测:

因此,解决 1 是最简单的:我们只需要使用内置的 didBegin(contact:)

我们将严重依赖 3 大位掩码:接触、类别和碰撞:

(仅供引用,我不喜欢在物理学中使用枚举和位数学,因为我是个叛逆的白痴):

struct BitMasks {
static let playerCategory = UInt32(2)
static let jupCategory = UInt32(4) // JUP = JumpUnderPlatform
}

override func didBegin(_ contact: SKPhysicsContact) {

// Crappy way to do "bit-math":
let contactedSum = contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask

switch contactedSum {

case BitMasks.jupCategory + BitMasks.playerCategory:
// ...
}

--

现在,你说你想使用 SKSEditor,所以我已经满足你了:

enter image description here enter image description here enter image description here enter image description here

// Do all the fancy stuff you want here...
class JumpUnderPlatform: SKSpriteNode {

var pb: SKPhysicsBody { return self.physicsBody! } // If you see this on a crash, then WHY DOES JUP NOT HAVE A PB??

// NOTE: I could not properly configure any SKNode properties here..
// it's like they all get RESET if you put them in here...
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
}

--

现在播放器:

class Player: SKSpriteNode {

// If you see this on a crash, then WHY DOES PLAYER NOT HAVE A PB??
var pb: SKPhysicsBody { return self.physicsBody! }

static func makePlayer() -> Player {

let newPlayer = Player(color: .blue, size: CGSize(width: 50, height: 50))
let newPB = SKPhysicsBody(rectangleOf: newPlayer.size)

newPB.categoryBitMask = BitMasks.playerCategory
newPB.usesPreciseCollisionDetection = true

newPlayer.physicsBody = newPB
newPlayer.position.y -= 200 // For demo purposes.

return newPlayer
}
}


2。 (并处理#4):确定是否在平台下联系:

有很多方法可以做到这一点,但我选择使用 KOD 提到的 player.pb.velocity.dy 方法来跟踪玩家的位置...如果你的 dy 是大于 0,则说明您正在跳跃(在平台下),否则说明您要么站着不动,要么跌倒(需要与平台接触并坚持下去)。

为了实现这一点,我们必须获得更多的技术支持,因为同样,物理系统和 SK 在其循环中的工作方式并不总是 100% 与我们认为它应该工作的方式相吻合.

基本上,我必须为 Player 创建一个 initialDY 属性,该属性在 update 中的每一帧不断更新

这个 initialDY 会为我们提供第一次接触平台所需的正确数据,让我们可以告诉我们更改碰撞掩码,并将玩家的 CURRENT dy 重置为初始 dy(因此玩家不会反弹)。


3。 (和处理#5):允许玩家通过平台

要通过平台,我们需要使用 collisionBitMasks。我选择让玩家的碰撞掩码 = 玩家的类别掩码,这可能不是正确的做法,但它适用于这个演示。

你最终在 didBegin 中得到了这样的魔法:

  // Check if jumping; if not, then just land on platform normally.
guard player.initialDY > 0 else { return }

// Gives us the ability to pass through the platform!
player.pb.collisionBitMask = BitMasks.playerCategory

现在,处理 #5 需要我们向玩家类添加另一个状态。我们需要临时存储联系的平台,以便我们可以检查玩家是否已成功通过平台(所以我们可以重置碰撞 mask )

然后我们只检查 didFinishUpdate 玩家的框架是否在该平台之上,如果是,我们重置 mask 。

这里是所有的文件,还有一个指向 github 的链接:
https://github.com/fluidityt/JumpUnderPlatform



播放器.swift:

class Player: SKSpriteNode {

// If you see this on a crash, then WHY DOES PLAYER NOT HAVE A PB??
var pb: SKPhysicsBody { return self.physicsBody! }

// This is set when we detect contact with a platform, but are underneath it (jumping up)
weak var platformToPassThrough: JumpUnderPlatform?

// For use inside of gamescene's didBeginContact (because current DY is altered by the time we need it)
var initialDY = CGFloat(0)
}

// MARK: - Funkys:
extension Player {
static func makePlayer() -> Player {

let newPlayer = Player(color: .blue, size: CGSize(width: 50, height: 50))
let newPB = SKPhysicsBody(rectangleOf: newPlayer.size)

newPB.categoryBitMask = BitMasks.playerCategory
newPB.usesPreciseCollisionDetection = true

newPlayer.physicsBody = newPB
newPlayer.position.y -= 200 // For demo purposes.

return newPlayer
}


func isAbovePlatform() -> Bool {
guard let platform = platformToPassThrough else { fatalError("wtf is the platform!") }

if frame.minY > platform.frame.maxY { return true }
else { return false }
}

func landOnPlatform() {
print("resetting stuff!")
platformToPassThrough = nil
pb.collisionBitMask = BitMasks.jupCategory
}
}

// MARK: - Player GameLoop:
extension Player {

func _update() {
// We have to keep track of this for proper detection of when to pass-through platform
initialDY = pb.velocity.dy
}

func _didFinishUpdate() {

// Check if we need to reset our collision mask (allow us to land on platform again)
if platformToPassThrough != nil {
if isAbovePlatform() { landOnPlatform() }
}
}
}


JumpUnderPlatform & BitMasks.swift(分别为:)

// Do all the fancy stuff you want here...
class JumpUnderPlatform: SKSpriteNode {

var pb: SKPhysicsBody { return self.physicsBody! } // If you see this on a crash, then WHY DOES JUP NOT HAVE A PB??

required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }

}

struct BitMasks {
static let playerCategory = UInt32(2)
static let jupCategory = UInt32(4)
}


GameScene.swift:

-

确保您的 SKS 编辑器中有两个节点: enter image description here enter image description here

-

// MARK: - Props:
class GameScene: SKScene, SKPhysicsContactDelegate {

// Because I hate crashes related to spelling errors.
let names = (jup: "jup", resetLabel: "resetLabel")

let player = Player.makePlayer()
}


// MARK: - Physics handling:
extension GameScene {

private func findJup(contact: SKPhysicsContact) -> JumpUnderPlatform? {
guard let nodeA = contact.bodyA.node, let nodeB = contact.bodyB.node else { fatalError("how did this happne!!??") }

if nodeA.name == names.jup { return (nodeA as! JumpUnderPlatform) }
else if nodeB.name == names.jup { return (nodeB as! JumpUnderPlatform) }
else { return nil }
}

// Player is 2, platform is 4:
private func doContactPlayer_X_Jup(platform: JumpUnderPlatform) {

// Check if jumping; if not, then just land on platform normally.
guard player.initialDY > 0 else { return }

// Gives us the ability to pass through the platform!
player.physicsBody!.collisionBitMask = BitMasks.playerCategory

// Will push the player through the platform (instead of bouncing off) on first hit
if player.platformToPassThrough == nil { player.pb.velocity.dy = player.initialDY }
player.platformToPassThrough = platform
}

func _didBegin(_ contact: SKPhysicsContact) {

// Crappy way to do bit-math:
let contactedSum = contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask

switch contactedSum {

case BitMasks.jupCategory + BitMasks.playerCategory:
guard let platform = findJup(contact: contact) else { fatalError("must be platform!") }
doContactPlayer_X_Jup(platform: platform)

// Put your other contact cases here...
// case BitMasks.xx + BitMasks.yy:

default: ()
}
}
}

// MARK: - Game loop:
extension GameScene {

// Scene setup:
override func didMove(to view: SKView) {
physicsWorld.contactDelegate = self
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
addChild(player)
}

// Touch handling: (convert to touchesBegan for iOS):
override func mouseDown(with event: NSEvent) {
// Make player jump:
player.pb.applyImpulse(CGVector(dx: 0, dy: 50))

// Reset player on label click (from sks file):
if nodes(at: event.location(in: self)).first?.name == names.resetLabel {
player.position.y = frame.minY + player.size.width/2 + CGFloat(1)
}
}

override func update(_ currentTime: TimeInterval) {
player._update()
}

func didBegin(_ contact: SKPhysicsContact) {
self._didBegin(contact)
}

override func didFinishUpdate() {
player._didFinishUpdate()
}
}

希望对您有所帮助!

关于ios - 试图制作我可以从下面跳过去但落在上面的平台。无法微调逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913398/

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