import scene in xna - c#

I have a scene that contains mutiple objects. How can i import it in xna and mentain each objects position? right now i export the scene in .fbx and load it in a model like this :
cube.model = contentManager.Load<Model>("cub");
but the objects don't retain their position and are all gathered in one point.
I need a method to import all the objects as individual objects but to retain the objects position in the scene?
(i.e. i need to import the scene so that i may manipulate the objects and retain their position in the scene so that i shouldn't reposition all the objects by myself)

Each object's scene position is in the fbx. The way to get it and implement it is to create a matrix array to hold every object's transform relative to the scene origin, then utilize the appropriate transforms when setting the effect.World for each object during draw time.
//class variables
Matrix[] objectTransforms;
//LoadContent section
cube.model = contentManager.Load<Model>("cub");
objectTransforms = new Matrix[cube.model.Bones.Count];
cube.model.CopyAbsoluteTransformsTo(objectTransforms);// the magic is done here
//draw method
foreach(ModelMesh mm in cube.model.Meshes)
{
foreach (BasicEffect bfx in mm.Effects)
{
bfx.World = objectTransforms[mm.ParentBone.Index] * whateverLocalTransformYouWant;
//draw here
}
}
Without utilizing 'objectTransforms' all objects will be drawn with their local origins located at the world origin, which sounds like what you are experiencing.

I personally made a level editor for most of the things in my game, but I do have a large scene in blender that links to other models. That way I can arrange all the level pieces in blender. When I export each individual piece, it does retain is global position and import correctly in the game. I would say that the issue resides in your fbx exporter. There should be an option to preserve location.
What modelling program do you use? If you use blender, there is an fbx exporter set made specifically for XNA that you should use.

Related

Text on Sprites in Unity

I'm trying to make an application that has sprites going down the screen with numbers in them. The Text(Script) component only works for 3D objects. I've tried using Text Mesh and making that a child of the sprites but I need them to be instantiated as a Prefab. So when I load the sprite in as a prefab it loses it's relationship to the Text Mesh. Does anyone know of a solution that worked for them?
There are many ways to do it depending upon your requirement. I will show you two of the most basic.
1- Use 2D Sprite and TextMesh.
2- Use Canvas Image and Text Objects.
P.S First one, that is 2D Sprite can be Instantiated directly in the hierarchy but for 2nd(Canvas Image) you need to instantiate it inside the canvas obj means as a child of canvas object.

Tiled object position doesn't match MonoGame position

I have an issue when importing Tiled maps with Object layers into a MonoGame project. Everything is pretty much working great; I can import the Tiled map into the project and render the map with the use of MonoGame.Extended.
My issue starts when I try to use an Object from an Object Layer in the Tiled map. I can access the object, and I can access its properties (position, etc) just fine. In fact, when accessing the object's properties, they output exactly as they should. Below are images to clarify:
This is the image of the object within the Tiled map editor
And below is the code where I import the map, collect the object's information, and assign that information (position, in this case) to another object (the player)
gameMaps.Add(MapBuilder.LoadTiledMap("TestMap"));
gameMapRenderer = new TiledMapRenderer(graphicsDevice);
var viewportAdapter = new BoxingViewportAdapter(GameInstance.Instance.Window, graphicsDevice, 1440 / 4, 810 / 4);
mainCamera = new Camera2D(viewportAdapter);
var player = new Player();
var playerStartPos = new Vector2();
foreach(var obj in gameMaps[0].ObjectLayers[0].Objects)
{
if (obj.Name.Equals("PlayerStart"))
{
playerStartPos = obj.Position;
break;
}
}
player.position = playerStartPos;
entities.Add(player);
mainCamera.LookAt(player.position);
But below is the image that demonstrates the issue:
Issue as an image
The sprite/character is the player object that is assigned the position, in case that wasn't clear.
To explain: I am able to get the object's position and assign it to my 'Player' object, and my player is then at the correct position per what the object's position is in the Tiled map editor. However, the Tiled map itself is actually rendering at an incorrect position- even though I never make any adjustments to the position of the map as a whole.
Some further details that might help:
In the Tiled map editor, the position x0,y0 is the utmost top tile of the map. However, in MonoGame, if I go the same position- the Tiled map is actually rendered/placed some dimensions below. This means that the positioning of the map is incorrect with what it should be.
Below is an image showing what that position is in MonoGame, and how it is not properly correlating with what that position is in Tiled.
MonoGame screenshot
After speaking a bit to the creator of Monogame.Extended, we narrowed down the issue. It was actually two things:
In the Tiled map editor, the grid system for isometric maps is different from the grid system Monogame uses to render everything. Tiled's grid system for isometric maps is a normal grid but rotated to match the isometric view, whereas Monogames is just a normal grid. This causes the position (x,y) of Objects in Tiled to be imported into Monogame with a position value that doesnt match with where it should actually be in Monogame- which explains the position being wrong in the image above. Monogame.Extended's creator took note on the bug but said a fix isnt certain because it would require a formula for converting an isometric Tiled position to a Monogame position.
Because my sprites had extra padding at the top, it was causing the overall map to render x many pixels lower than at what should be the proper 0 position. It had something to do with the map being generated in Monogame via the sprites dimensions, instead of the maps. Not a giant problem, honestly, since a workaround could be presumably made in a custom implementation of the TiledMapRenderer.
I can post the link to the Monogame.Extended discussion later.

Load existing GameObjects into a 2D array

I'm making a tile based board game (on a grid). In going about making the gameboard, the easy thing would be to instantiate all of the tiles in code, but then they only appear in play mode. I want to be able to edit the tiles in the editor, but I still want my tiles to be stored in a 2D array in my controller class. If I build the board in the editor, how might I go about loading them in at runtime?
Keep The Tiles in the Resources Folder Unity. At Run-time Load from the Resources and instantiate Tiles To Your Grid Positions in the Scene.
GameObject[] Tiles= (Resources.LoadAll<GameObject> ("Tiles"));

Unity 4.3 - 2D, how to assign programmatically sprites to an object

I'm trying to create an object that will be responsible of creating and showing different sprites, so I would like to access directly the assets/sprites programmatically instead of drag and drop a sprite in the hierarchy under that object.
There's a way to programmatically create a new sprite and assign what I have in the assets folder?
I also would like to have a sort of data structure with a few images loaded at the start of the game, an array or a dictionary or something like that so I can change based on some situation which images I need to show. But what confuses me since I'm new to Unity is how to create a sprite taking the reference to the sprite programmatically using the assets folder.
edit with progress:
I've created an array of sprites like this:
public Sprite[] mySprites;
in Unity I've added sprites inside the array manually (I just dragged png's inside the variable array) so actually in this Object I have a Component with this array full of sprites
inside the component I also have done this:
public SpriteRenderer renderer;
renderer = transform.GetComponent<SpriteRenderer>();
renderer.sprite = (Sprite)mySprites [0];
I got no error until I run the game, then the sprite is NOT assigned and I got this:
"PPtr cast failed when dereferencing! Castin from Texture2D to Sprite!"
I got this error even without casting (Sprite) and btw I don't know why he is telling my about Texture2D since verything is setted as sprite
To create a sprite programmatically might be a little too difficult to do. You'd probably need to create a Texture in memory, fill in the data, and then write that texture on the disk. After that, you should be able to read that using C#'s File, or Unity's WWW.LoadFromCacheOrDownload.
Here is how you would create a texture dynamically: http://answers.unity3d.com/questions/9919/how-do-i-create-a-texture-dynamically-in-unity.html
To load your sprites programmatically (not the ones created dynamically though), they need to be under a folder with the name Resources (which is a special folder).
I.e. suppose you have a sprite named MySprite.png under a folder named Sprites which is under a folder named Resources. You would then load it like this:
renderer.sprite = Resources.Load<Sprite>("Sprites/MySprite");
(notice how you do not include the Resources folder and the extension of the sprite)
You can find more details in the Loading Resources at Runtime documentation.
PPtr cast failed when dereferencing!
I did some searching and found out from this forum post that usually that happens when you had a list of one type and then changed it into another type. I.e. if mySprites was at some point GameObject[] and you linked a bunch of Sprites, and then changed it to Sprite[]. And since it specifically says Texture2D, I'm assuming that the import settings of your Sprites (or some of them) are set to Texture instead of Sprite:
Also, all MonoBehaviours have already a field named renderer, which is of type Renderer. I would suggest you rename that field to avoid confusion, unless you only used that as an example.
Here is real code.. will help you
void SetSprite(UI2DSprite uiSprite, Sprite[] sprites, string strKey)
{
foreach (Sprite stexture in sprites)
{
if (stexture.name == strKey)
{
uiSprite.sprite2D = stexture;
break;
}
}
}
use it following the way..
UI2DSprite[] uiSprites = tmpObject.GetComponentsInChildren<UI2DSprite>();
Sprite[] sprites = Resources.LoadAll<Sprite>("Textures");
string resName = "icon_favorite_2";
foreach (UI2DSprite uiSprite in uiSprites)
{
if(uiSprite.name = "icon")
SetSprite(uiSprite, sprites , resName);
}
Just to throw my tuppence worth in. I had this problem when I changed a SerializedField from Texture2D to Sprite in the code. The texture was already a sprite in the editor but it needed to be Sprite in the code. The field in the editor initially said type mismatch and then displayed the sprite texture again.
To cure it I set the field in the editor to none and the reset it to the required sprite.

Save cube in variable and apply scale/rotate/move OpenTK

I am creating simple 3D editor. I now can draw simple primitives like cube but, I don't know how to save this object to som variable and then copy it to other coordinates. I also don't know how rotate/scale/move this cube and save this new shape to variable. I have seen many tutorials on this topic, but in every one them, guy is moving only camera, not drawn object(cube). So basically I just need tutorial how to save some object to variable, than load this object from variable and draw it many times on different coordinates over scene and apply some transformation to these new objects(move,rotate,scale). I am creating this app in C# and OpenTK
Use the GL.Translate(x,y,z), GL.Rotate(θ,x,y,z) and GL.Scale(sx,sy,sz) functions to move the coordinate system origin, orientation and scaling.
So drawing a cube after the command
GL.Translate(10,10,100);
will draw the cube at the above location. Here is an (clunky) example of this process below:

Categories

Resources