【问题标题】:Calculate angle of SKShapeNode line on SpriteKit计算 SpriteKit 上 SKShapeNode 线的角度
【发布时间】:2020-04-29 12:26:22
【问题描述】:

我想制作一款积木游戏。 我有一个球想朝画线的方向射。

这是我的投篮方式:

 let ang = angle(between: balls.first!.position, ending: CGPoint(x: guideLine.frame.maxX, y: guideLine.frame.maxY))
    let force = CGVector(dx:cos(ang) * gameSpeed, dy:sin(ang) * gameSpeed)
    for i in 0..<balls.count {
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * 0.1) {
            if !balls.isEmpty {
                balls[i].physicsBody!.applyImpulse(force)
            }
        }
    }

这是我的“角度”函数,它将两个位置转换为角度:

func angle(between starting: CGPoint, ending: CGPoint) -> CGFloat {
    let center = CGPoint(x: ending.x - starting.x, y: ending.y - starting.y)
    let radians = atan2(center.y, center.x)
    let degrees = GLKMathRadiansToDegrees(Float(radians))
    return degrees > 0 ? CGFloat(degrees) : CGFloat(degrees + degrees)
}

如您所见,我从球所在的位置获取线的起点,并从线 maxX 和 maxY 本身获取线的终点...... 我不确定它的正确方法......

结果很奇怪!球会朝它想去的任何方向,每次都不一样(有时在我的线旁边,有时很远),我想不通。

以下是截图:

【问题讨论】:

    标签: swift sprite-kit nodes scenekit angle


    【解决方案1】:

    您正在计算以度为单位的角度,然后将其传递给sincos,它们需要弧度。这可能是您的主要问题。

    关于其他事情,目前尚不清楚所有degrees &gt; 0 的目的是什么。此外,最好在 SpriteKit 中坚持使用各种 SKActions 来处理延迟后运行的东西,而不是撒上 DispatchQueue 的东西。后者将无法与 SpriteKit 的暂停、更改节点速度等功能正确交互。

    let ang = angle(between: balls.first!.position, ending: CGPoint(x: guideLine.frame.maxX, y: guideLine.frame.maxY))
    let actions = [SKAction]()
    let force = CGVector(dx:cos(ang) * gameSpeed, dy:sin(ang) * gameSpeed)
    let wait = SKAction.wait(forDuration:0.1)   
    for ball in balls {
        let action = SKAction.run{
            ball.physicsBody!.applyImpulse(force)
        }
        actions.append(wait)
        actions.append(action)
    }
    run(SKAction.sequence(actions))  
    

    func angle(between starting: CGPoint, ending: CGPoint) -> CGFloat {
        let relativeToStart = CGPoint(x: ending.x - starting.x, y: ending.y - starting.y)
        let radians = atan2(relativeToStart.y, relativeToStart.x)
        //let degrees = GLKMathRadiansToDegrees(Float(radians))
        return radians > 0 ? (radians : (.pi * 2) + radians)
    }
    

    【讨论】:

    • 我猜他们想让它保持在 0 以上。所以应该是度数 + 360,而不是度数 + 度数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多