gpt4 book ai didi

ios - 如何根据平移手势速度将角脉冲应用于 Sprite Kit 节点

转载 作者:行者123 更新时间:2023-11-28 05:33:16 25 4
gpt4 key购买 nike

我在这里要做的是围绕其 anchor 旋转 SKSpriteNode 并使其速度和方向与平移手势相匹配。因此,如果我的平移手势是围绕 Sprite 顺时针旋转,那么 Sprite 会顺时针旋转。

我的代码存在的问题是,它非常适合在 Sprite 下方从左到右/从右到左平移,但当我尝试垂直平移时根本行不通,如果我这样做会使 Sprite 以错误的方式旋转在 Sprite 上方平移。

这是我到目前为止所得到的 -

let windmill = SKSpriteNode(imageNamed: "Windmill")

override func didMoveToView(view: SKView) {
/* Setup gesture recognizers */
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:")
self.view?.addGestureRecognizer(panGestureRecognizer)

windmill.physicsBody = SKPhysicsBody(circleOfRadius: windmill.size.width)
windmill.physicsBody?.affectedByGravity = false
windmill.name = "Windmill"
windmill.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
self.addChild(windmill)
}

func handlePanGesture(recognizer: UIPanGestureRecognizer) {
if (recognizer.state == UIGestureRecognizerState.Changed)
{
pinwheel.physicsBody?.applyAngularImpulse(recognizer.velocityInView(self.view).x)
}
}

我知道它不随垂直平移旋转的原因是我只得到 x 值,所以我想我需要以某种方式组合这些值。

我也尝试过使用 applyImpulse:atPoint:,但这会导致整个 Sprite 被扫除。

最佳答案

以下步骤将根据平移手势旋转节点:

  1. 存储一个从节点中心到平移手势起始位置的向量
  2. 从节点中心到平移手势结束位置形成一个向量
  3. 确定两个向量叉积的符号
  4. 计算平移手势的速度
  5. 使用速度和方向向节点施加角脉冲

这是一个如何在 Swift 中执行此操作的示例...

// Declare a variable to store touch location
var startingPoint = CGPointZero

// Pin the pinwheel to its parent
pinwheel.physicsBody?.pinned = true
// Optionally set the damping property to slow the wheel over time
pinwheel.physicsBody?.angularDamping = 0.25

声明 pan 处理程序方法

func handlePanGesture(recognizer: UIPanGestureRecognizer) {
if (recognizer.state == UIGestureRecognizerState.Began) {
var location = recognizer.locationInView(self.view)
location = self.convertPointFromView(location)
let dx = location.x - pinwheel.position.x;
let dy = location.y - pinwheel.position.y;
// Save vector from node to touch location
startingPoint = CGPointMake(dx, dy)
}
else if (recognizer.state == UIGestureRecognizerState.Ended)
{
var location = recognizer.locationInView(self.view)
location = self.convertPointFromView(location)

var dx = location.x - pinwheel.position.x;
var dy = location.y - pinwheel.position.y;

// Determine the direction to spin the node
let direction = sign(startingPoint.x * dy - startingPoint.y * dx);

dx = recognizer.velocityInView(self.view).x
dy = recognizer.velocityInView(self.view).y

// Determine how fast to spin the node. Optionally, scale the speed
let speed = sqrt(dx*dx + dy*dy) * 0.25

// Apply angular impulse
pinwheel.physicsBody?.applyAngularImpulse(speed * direction)
}
}

关于ios - 如何根据平移手势速度将角脉冲应用于 Sprite Kit 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26591500/

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