Azu*_*rld 3 objective-c sprite-kit
我正在尝试使用精灵表来为我的游戏制作动画.我如何从精灵表中删除每个精灵并在xcode中使用精灵?我目前正在使用obj -c.我在某处读到了我需要使用框架工作cocoa2d才能做到这一点?
小智 15
在精灵套件中,您可以使用SKTexture(rect: inTexture:)初始化程序剪切部分纹理.这是一个辅助类,它管理一个均匀间隔的精灵表,并可以在给定的行和列中剪切纹理.它像So一样使用
let sheet=SpriteSheet(texture: SKTexture(imageNamed: "spritesheet"), rows: 1, columns: 11, spacing: 1, margin: 1)
let sprite=SKSpriteNode(texture: sheet.textureForColumn(0, row: 0))
Run Code Online (Sandbox Code Playgroud)
这是完整的代码
//
// SpriteSheet.swift
//
import SpriteKit
class SpriteSheet {
let texture: SKTexture
let rows: Int
let columns: Int
var margin: CGFloat=0
var spacing: CGFloat=0
var frameSize: CGSize {
return CGSize(width: (self.texture.size().width-(self.margin*2+self.spacing*CGFloat(self.columns-1)))/CGFloat(self.columns),
height: (self.texture.size().height-(self.margin*2+self.spacing*CGFloat(self.rows-1)))/CGFloat(self.rows))
}
init(texture: SKTexture, rows: Int, columns: Int, spacing: CGFloat, margin: CGFloat) {
self.texture=texture
self.rows=rows
self.columns=columns
self.spacing=spacing
self.margin=margin
}
convenience init(texture: SKTexture, rows: Int, columns: Int) {
self.init(texture: texture, rows: rows, columns: columns, spacing: 0, margin: 0)
}
func textureForColumn(column: Int, row: Int)->SKTexture? {
if !(0...self.rows ~= row && 0...self.columns ~= column) {
//location is out of bounds
return nil
}
var textureRect=CGRect(x: self.margin+CGFloat(column)*(self.frameSize.width+self.spacing)-self.spacing,
y: self.margin+CGFloat(row)*(self.frameSize.height+self.spacing)-self.spacing,
width: self.frameSize.width,
height: self.frameSize.height)
textureRect=CGRect(x: textureRect.origin.x/self.texture.size().width, y: textureRect.origin.y/self.texture.size().height,
width: textureRect.size.width/self.texture.size().width, height: textureRect.size.height/self.texture.size().height)
return SKTexture(rect: textureRect, inTexture: self.texture)
}
}
Run Code Online (Sandbox Code Playgroud)
margin属性是图像边缘和精灵之间的差距.间距是每个精灵之间的间隙.fameSize是每个精灵的大小.这张图片解释了它:

| 归档时间: |
|
| 查看次数: |
4168 次 |
| 最近记录: |