Add custom “number” images to SKLabelNode in as a Score in SpriteKit with Swift

风流意气都作罢 提交于 2019-12-04 16:53:09
Mobile Ben

SKLabelNode would not allow for bitmap fonts. If your custom font was TTF, you would be able to use the custom font with SKLabelNode. An explanation how is here: SKlabelNode custom font

In your case, since you want to use bitmap fonts, you will need to create a class to do it do this. You can either subclass an SKNode or not. But you would want to have one SKNode act as the "root" and then have each digit for your number be an SKSpriteNode (these would be children nodes of the root node representing the number).

One thing you will want to determine is how you want to handle alignment for the number (both horizontally and vertically).

I have used my own custom class to draw numbers before and typically have it configurable to be adjustable horizontally (left justified, right justified, and centered). But out of laziness, I usually always center vertically.

This may sound complicated, but is easy to do. You would just need to have

  • Way to assign texture atlas of bitmaps for each digit. It is easier if you have them in progression of 0-9.
  • Method to set/get number value
  • Method which can convert number into individual digits. You'll need to this to compute which digit maps to which character.
  • Method to compute width of number. If your fonts are monospaced, then this is easy. If they are not, then you'll need to compute width based on digit width and letter-spacing. For monospaced font you still may want to factor in letter-spacing.
  • Method to compute height of number. This should be easy as 0-9 should all be the same height.
  • Method to remove existing SKSpriteNode and add each new digit. Each new digit being offset by the proper amount based on alignment.

Your custom class should, upon the number value being set, build the correct SKSpriteNodes to represent the number.

Some updated info for the last question regarding to how one would use an array with the SKTexture. This code is not tested for compilation and is meant to just give you a better idea.

// Example of storing digits in an array. Assumes you are putting this in an atlas and your
// sub-texture names are 0, 1, etc. If not you'll have to adjust the code accordingly
var numTextures = [SKTexture]()
let numberAtlas = SKTextureAtlas(named: "NumberAtlas")

for i in 0 ..< 10 {
    numTextures.append(numberAtlas.textureNamed("\(i)"))
}

// To get the texture for a digit

func textureForDigit(digit:Int) -> SKTexture {
    return numTextures[digit]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!