Quantcast
Channel: Questions in topic: "segment"
Viewing all articles
Browse latest Browse all 14

Segmenting image (at runtime) for puzzle pieces

$
0
0
Hi, I'm working on my first Unity project, a sliding puzzle ([like this][1]), and I'm struggling with splitting the texture (imported at runtime) into segments to fit the square pieces. Each tile is a default Sprite-GameObject. My current code: Texture2D image = Resources.Load ("Images/katze"); //Calculating the tile sizes float sizeX = image.width / numCols; float sizeY = image.height / numRows; //Take the smaller size (tiles are square) float tileSize = Mathf.Min(sizeX, sizeY); //I don't know the reason for this value, just played around :) float pixelsToUnits = tileSize / 8; //Get the topLeft point which acts as 'origin' for segmentingthe image Vector2 midPoint = new Vector2(image.width / 2, image.height / 2); Vector2 offset = new Vector2 (tileSize * numCols / 2, tileSize * numRows / 2); Vector2 topLeft = midPoint - offset; //new Vector2 (tileSize * numRows / 2, tileSize * numCols / 2); Vector2 pivot = new Vector2 (0.5f, 0.5f); // Center for (int x = 0; x < numCols; x++) { for(int y = 0; y < numRows; y++) { //The segment of the texture for this tile Rect rect = new Rect(topLeft.x + x * tileSize, topLeft.y + y * tileSize, tileSize, tileSize); Sprite tileSprite = Sprite.Create(image, rect, pivot, pixelsToUnits); grid[x, y] = createTile(x, y, tileSprite); //Instantiating the prefab and assigning the sprite } } Using this code, the resulting sprites are blurry (because of the texture being resized to the nearest power of two?) and I cannot handle non-square images (because of the texture being resized to a square). The reasons, why I do not simply use the Sprite Editor for segmenting the texture, are: - I want the players to use their own image for the puzzle - Number (and therefore size) of tiles is variable - Size of tiles may depend on aspect ratio I tried using planes and their uv maps, but my scaling code does not work with planes. That's why I ask before rebuilding it. :) Any help and comments for achieving this is appreciated! Thanks:) [1]: https://www.youtube.com/watch?v=T3EVFTEf1wU

Viewing all articles
Browse latest Browse all 14

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>