gpt4 book ai didi

swift 4 : SKSpriteNode won't stop on a position

转载 作者:行者123 更新时间:2023-11-30 11:55:36 27 4
gpt4 key购买 nike

这里我有一辆装有子弹的坦克,当用户点击屏幕时,坦克开火,没关系

但是当子弹从坦克中射出时,它会飞到屏幕上方,并且不会停在触摸位置

这是我的代码:

for touch in touches {
let location = touch.location(in: self)

let bullet = SKSpriteNode(imageNamed: "bullet4")

bullet.position = CGPoint(x: self.MainTank.position.x, y: self.MainTank.position.y + 10)

bullet.size = CGSize(width: 12, height: 20)

bullet.physicsBody = SKPhysicsBody(circleOfRadius: bullet.size.width / 2)

bullet.physicsBody?.affectedByGravity = false
bullet.physicsBody?.isDynamic = true // false stops the bullet on the tank
bullet.physicsBody?.allowsRotation = false
self.addChild(bullet)

var dx = CGFloat(location.x)
var dy = CGFloat(location.y)

let magnitude = sqrt(dx * dx + dy * dy)

dx /= magnitude
dy /= magnitude

let vector = CGVector(dx: 5.0 * dx, dy: 5.0 * dy)

bullet.physicsBody?.applyImpulse(vector)


}

我尝试将isDynamic设置为true,但这会使子弹停在坦克位置

谢谢

最佳答案

它可能会移动到屏幕之外,因为您将向量乘以 5.0。我也不会像那样创建你的向量,因为不需要带有大小的除法部分。试试这个:

let dx = location.x - bullet.position.x
let dy = location.y - bullet.position.y
let vector = CGVector(dx: dx, dy: dy)
bullet.run(SKAction.move(by: vector, duration: 1.0)) //choose your own duration of course

关于 swift 4 : SKSpriteNode won't stop on a position,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47856546/

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