# Unity converting Swift SpriteKit code to C# Script in Unity

This topic is 847 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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


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 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.transform.position = new Vector2 (xOffset + (i + 0.5)*blockWidth + (i - 1)*padding, (camHalfHeight*2)*0.8 );
block.name = "block";

}

}


Specifically,

1. Where is the most appropriate place to add this script?
2. How am I suppose to calculate the width of an image that I've added to the assets before I use it?
3. How do I represent CGFloat padding = 10.0 in Unity?
4. 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?

1. 1
2. 2
Rutin
24
3. 3
4. 4
JoeJ
19
5. 5

• 14
• 26
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631771
• Total Posts
3002253
×