根据触摸位置以一定角度施加脉冲

Applying impulse at angle based on touch location

我目前正在开发一款使用大炮发射弹丸的游戏,我无法弄清楚如何根据触摸位置以及它与大炮。这是我在下面使用的代码。

let dx = cannon.position.x - (touchLocation.x)
        let dy = cannon.position.y - (touchLocation.y)
        let angle = atan2(dy, dx)

        bullet.zRotation = angle
        bulletspeed = Double.random(in: 1...6)

        //let angle1 = Double.random(in: 0.2...5); let angle2 = Double.random(in: 1...4)

        // dx must be somewhere between 0.2 to 5
        bullet.physicsBody?.applyImpulse(CGVector(dx: -angle , dy: -angle))

这似乎不起作用,我已经使用角度作为我的 x 和 y 值,但效果不佳。

我试图让大炮根据触摸位置的角度开火,并根据触摸位置与大炮的距离来改变射弹的 speed/power。 我该怎么做?

您需要使用的向量以dx和dy为参数。你已经有了这些但是你说速度太快了。那是因为向量的长度就是速度。

因此在您的示例中,速度可以这样计算...

sqrt(dx*dx+dy*dy)

你需要做的是计算一个“单位向量”,即长度等于一的向量。

您可以通过将 dx 和 dy 除以向量的长度来实现。

所以...

touchDX = //your calculation
touchDY = //your calculation

touchLength = sqrt(touchDX*touchDX+touchDY*touchDY)

unitVectorDX = touchDX / touchLength
unitVectorDY = touchDY / touchLength

// now put the speed you want in...

speed = 10

vector = CGVector(dx: unitVectorDX * speed, dy: unitVectorDY * speed)

现在,如果您在脉冲中使用矢量,它将具有正确的方向和速度。

快速旁注,我在 iPad 上打字,所以无法访问代码完成等...您可以使用 CGVector 上的 API 来完成此操作。我想我记得一个“unitVector”属性,returns 一个单位向量。但我可能错了。