gpt4 book ai didi

ios - 生成随机颜色并将其分配给对象

转载 作者:行者123 更新时间:2023-11-29 01:41:32 32 4
gpt4 key购买 nike

我想让Obstacle_Color = random 颜色而不是blackcolor。我找到了随机颜色实现,但无法将 `Obstacle_Color 与 rand 方法的返回值合并。提前致谢!

import Foundation
import SpriteKit

class AKObstacle: SKSpriteNode {

let Obstacle_Width: CGFloat = 40.0
let Obstacle_Height: CGFloat = 70.0
let Obstacle_Color = UIColor.blackColor()

init(){

let size = CGSizeMake(Obstacle_Width, Obstacle_Height)
super.init(texture: nil, color: Obstacle_Color, size: size)

loadPhysicsBoadyWithSize(size)
startMoving()

}

func getRandomColor() -> UIColor{

var randomRed:CGFloat = CGFloat(drand48())

var randomGreen:CGFloat = CGFloat(drand48())

var randomBlue:CGFloat = CGFloat(drand48())

return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)

}

最佳答案

一个解决方案是让 get randomcolor 成为一个静态函数,并将其作为类方法调用。另一个方法(可能更好,因为该函数似乎并没有专门链接到该类)是使它成为一个公共(public)方法。还有人建议在构造函数中调用它,这也有效。

方案一

import UIKit
import Foundation
import SpriteKit

class AKObstacle: SKSpriteNode {

let Obstacle_Width: CGFloat = 40.0
let Obstacle_Height: CGFloat = 70.0
let Obstacle_Color = AKObstacle.getRandomColor()

init() { ... }

static func getRandomColor() -> UIColor {

var randomRed:CGFloat = CGFloat(drand48())

var randomGreen:CGFloat = CGFloat(drand48())

var randomBlue:CGFloat = CGFloat(drand48())

return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
}

解决方案2

import UIKit
import Foundation
import SpriteKit

class AKObstacle: SKSpriteNode {

let Obstacle_Width: CGFloat = 40.0
let Obstacle_Height: CGFloat = 70.0
let Obstacle_Color = getRandomColor()

init() {...}

}

public func getRandomColor() -> UIColor {

var randomRed:CGFloat = CGFloat(drand48())

var randomGreen:CGFloat = CGFloat(drand48())

var randomBlue:CGFloat = CGFloat(drand48())

return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}

关于ios - 生成随机颜色并将其分配给对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32331982/

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