SKSpriteKit在碰撞后保持恒定速度 [英] SKSpriteKit maintaining constant velocity after collision

查看:230
本文介绍了SKSpriteKit在碰撞后保持恒定速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作我的第一个iOS应用,目前遇到了问题.

I am attempting to make my first iOS app and currently running into an issue.

在我的游戏中,当球反弹时,我希望球反弹回相同的高度并以相同的速度弹回.目前,它做得很好.但是,当我旋转六边形并碰到一个角度时,它最终会失去速度并且不会反弹到相同的高度.

In my game, when the ball bounces I want it to bounce back to the same height and with the same velocity. Currently it does that just fine. However, when I rotate the hexagon and it hits an angle, it ends up losing speed and not bouncing to the same height.

所以我的问题是:碰撞时如何迫使球保持相同的速度?

So my question is: How do I force the ball to maintain the same velocity upon collision?

这是我的Ball节点的代码:

Here is the code for my Ball node:

func createBallNode(ballColor: String) -> SKSpriteNode {
    let ball = SKSpriteNode(imageNamed: ballColor)
    ball.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)+30)
    ball.zPosition = 1

    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)
    ball.physicsBody?.affectedByGravity = true
    ball.physicsBody?.restitution = 1
    ball.physicsBody?.linearDamping = 0
    ball.physicsBody?.friction = 0

    ball.physicsBody?.categoryBitMask = ColliderType.Ball.rawValue
    ball.physicsBody?.contactTestBitMask = ColliderType.Rect.rawValue
    ball.physicsBody?.collisionBitMask = ColliderType.Rect.rawValue

    let centerX = ball.position.x
    let range = SKRange(lowerLimit: centerX, upperLimit: centerX)

    let constraint = SKConstraint.positionX(range)
    ball.constraints = [constraint]

    return ball
}

下面是一个GIF,以可视形式解释了该问题:

Below is a GIF explaining the problem in a visual form:

推荐答案

我不确定您是否还在寻找答案,但是...

I'm not sure if you are still looking for an answer, but...

如果您始终希望球在相同的垂直方向弹跳,那为什么不呢?

If you always want the ball to bounce on the same vertical, then why don't you:

  • 在六角形的底线所在的位置创建一个水平的SKShapeNode.
  • 将填充和描边颜色设置为透明".
  • 为其设置物理物体-以便球在其上弹跳.
  • 从彩色六边形形状中移除物理物体.

这将避免任何角度反弹"问题.

This'll avoid any 'bouncing on angles' issues.

如果要检测与相关十六进制形状的接触,可以跟踪底部的内容,或者:

If you want to detect contact with the relevant hex shape, you could keep track of what is at the bottom, or:

  • 将新的物理框向下移动1点.
  • 在您的六边形形状(而不是碰撞")中添加防毒面具,以便您获得接触但没有物理碰撞.
  • Move the new physics box 1 point down.
  • Add contact mask to your hexagon shapes (not 'collision') so you get contacts but no physical collision.

这篇关于SKSpriteKit在碰撞后保持恒定速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆