I am trying to convert to following code from Swift SpriteKit to a C# Script in Unity. Coming from a SpriteKit point of view, the coordinate system in Unity is quite confusing. Basically, all I've been able to do is declare the variables. I would appreciate any assistance. Please see the code below (Swift SpriteKit):
let numberOfBlocks = 5
let blockWidth = SKSpriteNode(imageNamed: "block.png").size.width
let totalBlocksWidth = blockWidth * CGFloat(numberOfBlocks)
let padding: CGFloat = 10.0
let totalPadding = padding * CGFloat(numberOfBlocks - 1)
let xOffset = (CGRectGetWidth(frame) - totalBlocksWidth - totalPadding) / 2
for i in 0..<numberOfBlocks {
let block = SKSpriteNode(imageNamed: "block.png")
block.position = CGPointMake(xOffset + CGFloat(CGFloat(i) + 0.5)*blockWidth + CGFloat(i-1)*padding, CGRectGetHeight(frame) * 0.8)
block.physicsBody = SKPhysicsBody(rectangleOfSize: block.frame.size)
block.physicsBody!.allowsRotation = false
block.physicsBody!.friction = 0.0
block.physicsBody!.affectedByGravity = false
block.name = BlockCategoryName
block.physicsBody!.categoryBitMask = BlockCategory
addChild(block)
}
Below is what I've been able to work on so far (C# Script).
void Start () {
int numberOfBlocks = 5;
float blockWidth = "SKSpriteNode(imageNamed: "block.png").size.width;" // How am I suppose to calculate the width of an image that I've added to the assets before I use it //GetComponent<SpriteRenderer> ().bounds.size.x;
float totalBlocksWidth = blockWidth * numberOfBlocks;
float padding = 10.0; // how am I suppose to represent this in Unity?
float totalPadding = padding * (numberOfBlocks - 1);
float camHalfHeight = Camera.main.orthographicSize;
float xOffset = ((Camera.main.aspect * camHalfHeight) * 2 - totalBlocksWidth - totalPadding) / 2;
for (int i = 0; i < numberOfBlocks; i++) {
GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube);
block.AddComponent<SpriteRenderer>().sprite = blockSprite;
block.AddComponent<BoxCollider2D>();
block.transform.position = new Vector2 (xOffset + (i + 0.5)*blockWidth + (i - 1)*padding, (camHalfHeight*2)*0.8 );
block.name = "block";
}
}
Specifically,
- Where is the most appropriate place to add this script?
- How am I suppose to calculate the width of an image that I've added to the assets before I use it?
- How do I represent CGFloat padding = 10.0 in Unity?
- Above I have calculated CGRectGetWidth(frame) as (Camera.main.aspect * camHalfHeight) * 2 based on a post I saw. Is there a better way to go about this calculation?
Thanks in advance.