Add custom “number” images to SKLabelNode in as a

2019-04-15 04:06发布

问题:

I basically want to add custom font numbers (with images) in Singles and add them for my score in my game with SpriteKit.

This is the font image style

They are numbers from 0 to 9

I have been trying to figure this out for a while.

I'm not sure if you can add it to SKLabelNode or if you would have to make it in a class.

回答1:

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]
}