在我的代码中,我试图制作一个正方形跟随用户触摸和保持的位置,但是当我尝试编码时,正方形随机随处可见并且不会跟随用户的位置握住他们的手指。有人可以帮我修改这段代码吗?
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
var speedOfTouch = CGFloat(30)
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if location.x < CGRectGetMidX(self.frame) {
square.position.x <= speedOfTouch
square.physicsBody?.applyImpulse(CGVector(dx: -10 , dy: 0))
}
else {
square.position.x >= speedOfTouch
square.physicsBody?.applyImpulse(CGVector(dx: 10, dy: 0))
}
}
}
答案 0 :(得分:0)
您应该将触摸的位置与广场的当前位置进行比较,而不是中心(我猜测是广场的第一个位置)
物理学:
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
var speedOfTouch = CGFloat(30)
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if location.x < square.position.x {
square.position.x <= speedOfTouch
square.physicsBody?.applyImpulse(CGVector(dx: -10 , dy: 0))
}
else {
square.position.x >= speedOfTouch
square.physicsBody?.applyImpulse(CGVector(dx: 10, dy: 0))
}
}
}
没有物理学:
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
var speedOfTouch = CGFloat(30)
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
square.position = CGPointMake(location.x, square.position.y)
}
}