- Home /
Instantiate Left-Edge of Prefab at Right-Most Edge of Another
So I'm working on some randomly generated content and I've broken up my platforms into "frames"
When I get to placing a new frame I want to position it so its left edge is next to the left most edge of the previous one.
I keep track of the current right most frame in the code and here's my code where I instantiate the next frame:
rightMostFrame = (GameObject)Instantiate( frameToAdd,
rightMostFrame.transform.position + rightMostFrame.transform.right * rightMostFrameComponent.offset - rightMostFrame.transform.up * rightMostFrameComponent.transform.position.y,
transform.rotation );
Frame to add are a bunch of prefabs that consist of a couple models as children. One of these models is the actual platform I want to position along the previous.
The code above, specifically rightMostFrameComponent.offset, comes from another script where I store data for each frames. I figure this would be useful. At creation of these frames I make this offset property equal to the X size of the objects renderer
offset = floor.renderer.bounds.size.x;
I'm having trouble mapping out exactly how I should do this. I need the center of the new frame to be offset from the right edge of the previous frame enough so that the left side of the new frame is at the same X and Z coordinate.
Any ideas?
Answer by sharp7j · Nov 14, 2015 at 07:23 PM
So I don't know if this will work, but this is how I plan to do it.
You could go through all the objects in the previous prefab, get their x position and their widths, then see which one has the highest width+position (might be width/2+position?). That should be the right most point, however I don't know how to do this with rotations included.
Then to the prefab you want to add, you would do the same thing but get the left and right most points. You would want the right AND left most point just to get the total width of it. Then you would just create the prefab at I think old right most point+(total width of new prefab)/2.
Something like that might work if rotations aren't happening.
I think there might be something you can do with checking the rendering of the sprite as well?