我正在创建一些功能,以便使一个游戏类似于Flappy Bird。我是一个完全的初学者,并试图了解一切,因为我走之前,继续。我已经能够让我的障碍移动,但当我试图把它变成一个函数,让我更灵活,后来有多个障碍,我会收到一个错误。
'无法将类型')'转换为所需的参数类型'SKAction'
类游戏场景:SKScene,skphysiccontactdelegate{
var Player = SKSpriteNode()
var Ground = SKSpriteNode()
var Roof = SKSpriteNode()
var Background = SKSpriteNode()
let Obstacle1 = SKSpriteNode(imageNamed: "Fire Barrel 1")
override func didMove(to view: SKView) {
// Create Background Color
backgroundColor = bgColor
// Set World Gravity
self.physicsWorld.gravity = CGVector(dx: 0.0, dy: -4.0)
// Create Player
Player = SKSpriteNode(imageNamed: "Player")
Player.setScale(0.5)
Player.position = CGPoint(x: -self.frame.width / 2 + 100, y: -Player.frame.height / 2)
self.addChild(Player)
// Create Ground
Ground = SKSpriteNode(imageNamed: "BGTileBtm")
Ground.anchorPoint = CGPoint(x: 0,y: 0.5)
Ground.position = CGPoint(x: -self.frame.width / 2, y: -self.frame.height / 2)
self.addChild(Ground)
// Create Roof
Roof = SKSpriteNode(imageNamed: "BGTileTop")
Roof.anchorPoint = CGPoint(x: 1,y: 1)
Roof.position = CGPoint(x: -self.frame.width / 2, y: self.frame.height / 2 - Roof.frame.height)
Roof.zRotation = CGFloat(M_PI)
self.addChild(Roof)
// Set Physics Rules
Player.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "Player"), size: Player.size)
Player.physicsBody!.affectedByGravity = true
Player.physicsBody!.allowsRotation = false
Ground.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "Ground"), size: Ground.size)
Ground.physicsBody!.affectedByGravity = false
Ground.physicsBody!.isDynamic = false
// Obstacle
func addObstacle1(){
Obstacle1.position = CGPoint(x: self.frame.width / 2, y: -self.frame.height / 2 + Obstacle1.frame.height)
Obstacle1.zPosition = 1
addChild(Obstacle1)
}
func moveObstacle1(){
let distance = CGVector(dx: -self.frame.width, dy: 0)
let moveDistance = SKAction.move(by: distance, duration: 5)
run(moveDistance)
}
addObstacle1()
Obstacle1.run(moveObstacle1())
}
最佳答案
将moveObstacle1
的声明更改为:
func moveObstacle1() -> SKAction{
let distance = CGVector(dx: -self.frame.width, dy: 0)
let moveDistance = SKAction.move(by: distance, duration: 5)
return moveDistance
}
编辑:
关于你的评论,
run
是一种方法。当你调用它时,它运行你传入的SKAction。就这样!你要做的是run(moveObstacle1())
。那到底是什么意思?如何将方法调用作为参数传递?在运行时,moveObstacle1()
的返回值传递给run
。换句话说,要编译run(moveObstacle1())
,moveObstacle1()
必须使用return
语句返回一个值。这个值必须是SKAction
类型,因为这是您传递给run
的内容。return
用于从moveObstacle1()
返回值,以便您可以调用run(moveObstacle1())
。run
只是一种常规的老方法。关于swift - Swift 3预期参数错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40074479/