在我的SpriteKit项目中,我有一只船,我左右拖动它来捕捉从天上掉下来的物品,我希望船朝着它移动的方向看,我想我必须将xScale从CGFloat(1)更改为CGFloat(-1),但我不知道如何处理,任何建议都值得赞赏,这是我处理船移动的方式:

class GameScene: SKScene{

var node = SKSpriteNode()
var nodePosition = CGPoint()
var startTouch = CGPoint()


override func didMove(to view: SKView) {
    self.anchorPoint = CGPoint(x: 0.5, y: 0.5)

    // node set up
    node = SKSpriteNode(color: .red, size: CGSize(width: 50, height: 50))
    node.position = CGPoint.zero
    self.addChild(node)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    if let location = touch?.location(in: self){
        startTouch = location
        nodePosition = node.position
    }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    if let location = touch?.location(in: self){
        node.run(SKAction.move(to: CGPoint(x:  nodePosition.x + location.x - startTouch.x, y: nodePosition.y + location.y - startTouch.y), duration: 0.1))
    }
}

}

推荐答案

touchesMoved中,可以使用touch.locationtouch.previousLocation来确定x位置的变化.然后,如果delta x为正或负,则可以相应地翻转xScale.

//grab current and previous locations
let touchLoc = touch.location(in: self)
let prevTouchLoc = touch.previousLocation(in: self)

//get deltas and update node position
let deltaX = touchLoc.x - prevTouchLoc.x
let deltaY = touchLoc.y - prevTouchLoc.y
node.position.x += deltaX
node.position.y += deltaY

//set x flip based on delta
node.xScale = deltaX < 0 ? 1 : -1

Ios相关问答推荐

SwiftUI中ForEach和@ State数组的可能并发问题

如何使视图完全适合屏幕,而不会在旋转时溢出手机屏幕的边界?

Xcode版本15.2上未显示iOS 16.4的模拟器

使用AVCaptureEventInteraction捕获音量按键快门

SWIFT-仅解码感兴趣的元素

在将Cocoapods更新到1.13.0之后,它抛出错误

确保方法调配的安全有效实施

为什么常量属性可能在 Swift 类中被初始化两次?

无法验证客户端 3000

如何启用滑动以删除 TableView 中的单元格?

UIView 和 initWithFrame 以及一个 NIB 文件.如何加载 NIB 文件?

使用 convertPoint 获取父 UIView 内的相对位置

正确的领域使用模式/最佳实践?

Swift 将 unix 时间转换为日期和时间

自动布局:是什么创建了名为 UIView-Encapsulated-Layout-Width & Height 的约束?

有什么方法可以加粗 NSString 的一部分?

更新字段时,UITextField值已更改未触发

NSURL 到带有 XCTest 的测试包中的文件路径

Info.plist 实用程序错误:无法打开 Info.plist,因为没有这样的文件

如何使用 UISegmentedControl 切换视图?