Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floats SpriteKit

Why does SpriteKit use floats for position even though there can't be a decimal point in pixels?

I am building a game in SpriteKit and am wondering whether I should make the character position in ints to optimize it but am not sure whether there will be any performance improvements.

Is it worth converting the character positions to ints to optimize?

like image 471
half-potato Avatar asked Jun 13 '26 10:06

half-potato


2 Answers

In general, it's simpler to use floats than integers when dealing with graphics above the bit-twiddling level. Note that Core Graphics also uses floats for coordinates.

The reason it's simpler is that you want to do things like scale (by a non-integer factor) and rotate coordinates, images, paths, etc. If you use integers, the rounding errors accumulate by a noticeable amount quickly. If you use floats, the rounding errors take much longer to become noticeable - usually they don't become noticeable at all.

Also consider that an SKNode has xScale and yScale properties. If you scale up a node, the fractional part of its children's positions can have a large effect on their positions on the screen.

You should not convert your character positions to ints. SpriteKit uses floats, so you'll end up converting them back to floats to use them with SpriteKit, the CPU has floating point support, and the GPU is designed to perform massive amounts of floating point arithmetic.

like image 66
rob mayoff Avatar answered Jun 14 '26 23:06

rob mayoff


The other answers are good, but keep in mind that you are NOT working in pixels: you are working in points. Depending on the device, points will hold more or less pixels. The reason behind that was to accommodate the retina displays that had the save physical size. You work with points, and when you add pixels, everything still lines up because the number of pixels per point increased, but the number of points in the screen stayed the same.

like image 35
BadgerBadger Avatar answered Jun 15 '26 00:06

BadgerBadger