gpt4 book ai didi

xcode - 使用图像作为 Sprite 角色

转载 作者:行者123 更新时间:2023-11-30 10:01:25 25 4
gpt4 key购买 nike

所以我正在开发一款游戏,并在我的 swift 2 spritekit 游戏中使用一个球。我有一个 make ball 函数,在游戏场景中,当调用该方法时,我不断收到此错误:“无法分配 SKShapeNode”来输入 Ball!我不知道如何修复,并且是 swift 新手。谢谢!

// ----- GameScene.Swift ----
class GameScene: SKScene, GameDelegate, SKPhysicsContactDelegate {
// ball part one
var ball: Ball!
let ballSpeedX = CGFloat(500)
}

override func didMoveToView(view: SKView) {
// ball
ball = Ball.make() // error!!!
ball.position.x = CGRectGetMidX(self.frame)
ball.position.y = CGRectGetMidY(self.frame)
ball.physicsBody!.categoryBitMask = CollideType.Ball.toMask()
ball.physicsBody!.collisionBitMask = CollideType.toMask([.Scene, .Ceil, .Floor]) | boards.usedCollideMasks
ball.physicsBody!.contactTestBitMask = CollideType.toMask([.Scene, .Ceil, .Floor]) | boards.usedCollideMasks
ball.hidden = true
self.addChild(ball)
}

然后这是 ball.swift,其中 make() 是//Ball。 swift

//imports...

class Ball: SKShapeNode {

var speedXFirst = CGFloat(0)
var speedXSecond = CGFloat(0)
var lastFloor = -1

var xSpeed: CGFloat {
get {
return speedXFirst + speedXSecond
}
}

var lastBoardNumber = 0

private override init() {
super.init()
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

static func make()-> SKShapeNode {

let textureBall : SKTexture! = SKTexture(imageNamed:"colorBall.png")
let ballSize: CGSize = textureBall.size()
var ball = SKShapeNode.init(circleOfRadius: ballSize.width/2)
ball.fillTexture = textureBall
ball.strokeColor = UIColor.clearColor()
ball.name = "ball"
ball.zPosition = 1
ball.fillColor = UIColor.redColor() // use the color you want
return ball
}

func freezeX() {
self.speedXFirst = 0
self.speedXSecond = 0
}
}

最佳答案

要成功执行 ball = Ball.make()make() 方法的返回类型需要为 Ball,而不是 SKSpriteNode.

要从 make() 返回 Ball 值,您需要创建 Ball 的实例,而不是 SKSpriteNode.

static func make() -> Ball {  //the return type of `make()` method needs to be `Ball`

let textureBall : SKTexture! = SKTexture(imageNamed:"colorBall.png")
let ballSize: CGSize = textureBall.size()
let ball = Ball(circleOfRadius: ballSize.width/2) //you need to create an instance of `Ball`
ball.fillTexture = textureBall
ball.strokeColor = UIColor.clearColor()
ball.name = "ball"
ball.zPosition = 1
ball.fillColor = UIColor.redColor()
return ball
}

关于xcode - 使用图像作为 Sprite 角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38279519/

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