Raylib for Swift 使用 Swift 的 C 互操作性和编译器从源代码构建 Raylib。 只需将该软件包添加为依赖项(到您的 swift 可执行软件包),即可开始制作游戏!
在 Windows 和 macOS 上,您只需要 Swift。 对于 Linux,请参阅 安装所需的库。
1. 为您的项目创建一个 Swift 包。
$ cd my/projects/folder/path
$ mkdir MyGame
$ cd MyGame
$ swift package init --type executable
2. 编辑新创建的 Package.swift
文件,将 Raylib 添加到依赖项数组
.package(url: "https://github.com/STREGAsGate/Raylib.git", branch: "master")
在 Windows 和 macOS 上,您只需要 Swift。 对于 Linux,请参阅 安装所需的库。
注意:需要
.branch("master")
,您不能使用标签、提交或版本。 Swift 不允许为特定版本使用不安全的构建标志,并且构建 Raylib 需要构建标志,因此您目前必须使用 master,否则您将收到来自 SwiftPM 的错误。
3. 将以下内容添加到 MyGame.swift 中的 static func main()
。
let screenWidth: Int32 = 800
let screenHeight: Int32 = 450
Raylib.initWindow(screenWidth, screenHeight, "MyGame")
Raylib.setTargetFPS(30)
let randomColors: [Color] = [.blue, .red, .green, .yellow, .darkBlue, .maroon, .magenta]
var ballColor: Color = .maroon
var ballPosition = Vector2(x: -100, y: -100)
var previousBallPosition: Vector2
while Raylib.windowShouldClose == false {
// update
previousBallPosition = ballPosition
ballPosition = Raylib.getMousePosition()
if Raylib.isMouseButtonDown(.left) {
ballColor = randomColors.randomElement() ?? .black
}
let size = max(abs(ballPosition.x - previousBallPosition.x) + abs(ballPosition.y - previousBallPosition.y), 10)
// draw
Raylib.beginDrawing()
Raylib.clearBackground(.rayWhite)
Raylib.drawText("Hello, world!", 425, 25, 25, .darkGray)
Raylib.drawCircleV(ballPosition, size, ballColor)
Raylib.drawFPS(10, 10)
Raylib.endDrawing()
}
Raylib.closeWindow()
原始 Raylib 全局函数现在是 Raylib
类型的静态成员。
Raylib.initWindow(screenWidth, screenheight, "My First Raylib Window!")
这个项目的目标是将所有全局函数作为成员提供在它们各自的类型上。
例如,Image
现在有了新的初始化器。
let image = Image(color: .green, width: 256, height: 256)
为整个 API 执行此操作将提高可发现性,并使 Raylib for Swift 具有更 Swift 的体验。