draw 2d string in 3d space xna
Introduction
This is an update of the Star Trek XNA demonstration in which I ported from Visual Studio Express to Visual Studio 2005 and XNA 2.0. Information technology adds a more realistic looking Klingon transport and a rotating 3D Planet. In this article we will discuss how to add 3D Objects and Text to your games. MeshesThe planet consists of a sphere mesh coated with a 2D Texture. Meshes are a set of vertices in 3D space that draw a 3D Object. You can create meshes using professional person tools such as Maya and 3D Studio. You tin also create meshes with an open source tool such as blender. Blender takes a bit of skill to learn, but if you follow the tutorials, you lot'll soon be creating some interesting 3D Meshes. XNA supports the direct-x format (*.x) for meshes so y'all'll demand to consign your mesh in this format. Once you lot have a mesh, you can easily read and manipulate it using the objects in XNA. Effigy 1 Star Trek Below is the code to read a Mesh into your game: Listing 1 - Loading a 3D Mesh ModelMesh _Sphere; // this is the mesh object
protected override void LoadGraphicsContent(bool loadAllContent)
{
if (loadAllContent)
{
// this line loads the Mesh from a directly 10 file (with the .ten extension)
_Sphere = content.Load<Model>((@"Content\Textures\Sphere1")).
Meshes[0];
} One time we take a mesh we need to position the mesh, scale the mesh, and add a texture to the mesh. All of these deportment are accomplished by changing the Furnishings of the mesh. Each basic result of the Effects drove has properties such every bit earth coordinates, lighting, and textures to permit us to manipulate the mesh structure. List 2 shows the method for positioning our sphere on the screen and calculation a bitmap texture to its surface. All transforms are performed using a 3D Matrix. XNA gives us a Matrix class that makes it unproblematic to create our transforms. The calibration matrix is created using the CreateScale method with a single scalar value relative to the game surface. A value of 1.0 indicates the entire game surface. The calibration matrix is then multiplied past the Globe coordinates of the Result to get the appropriate scaling of our 3D object. The sphere is moved around the screen using a translation matrix created from the CreateTranslation method using a 3D commencement vector. The translation is performed in 3D space relative to View coordinates. A coordinate of (one, 0, 0) positions the planet where we want it, to the far right and centered vertically.
Textures are also assigned to the Issue through the Texture property. The 2nd texture that was loaded in the LoadGraphicsContent method is assigned to an effect to give u.s.a. a texture on the surface of our mesh. Listing 2 - Changing the Effects of the Mesh
private void SetDefaultMeshEffects(ModelMesh mesh, float calibration, Vector3 position, Texture2D texture)
{
foreach (BasicEffect outcome in mesh.Effects)
{
effect.EnableDefaultLighting(); // set default lighting
result.World = effect.World * Matrix.CreateScale(scale); // scale the globe coordinates
effect.Texture = texture;
effect.View = Matrix.CreateTranslation(position);
event.TextureEnabled = true;
}
}
Rotating the Planet
The planet is rotated by changing transforming the rotation of the sphere every time it enters the Update method of the Game object. Over again, the effect of the planet mesh is multiplied by a transformation matrix to rotate the sphere. In this instance we rotate the sphere .02 radians around the X and the Z axises.
Listing iii - Rotating the Planet Every Time an Update is Called
/// <summary>
/// This is called from the Update Method
/// </summary>
private void RotatePlanet()
{
// go through each issue in the sphere and rotate information technology's
// world coordinates .02 radians effectually the 10 and Z
// Axises
foreach (BasicEffect consequence in _Sphere.Effects)
{
event.EnableDefaultLighting();
upshot.Globe = effect.World * Matrix.CreateRotationX(-.02f) * Matrix.CreateRotationZ(-.02f);
}
}
Joystick Motility
XNA makes decision-making an XBox joystick a snap with its built in GamePad class. By just reading the state of the pad, you lot tin get button information and thumbstick positions with a few like shooting fish in a barrel to use static methods. The method UpdateFromGamePad shown in listing four is called from Update in the game class. In keeping with the keypad command, we decided to utilise the left thumbstick to move forward and backward and the right thumbstick to rotate clockwise and counterclockwise. What is overnice nearly the joystick classes in XNA is the code is almost cocky-explanatory. Y'all tin can get the state of a particular button and meet if it was pressed or released, or y'all tin get the state of a thumbstick (Left or Right) and see its 10 and Y position vector. In list four we round the left thumbstick's X vector positions in lodge to determine if we are moving forward or astern. A value of 1 indicates forward and a value of -1 indicates astern. We use the same technique for rotation. We round the correct thumbstick'southward X vector positions in order to determine if we are rotating clockwise or counterclockwise. A value of 1 indicates clockwise and a value of -1 indicates counter clockwise.
Listing 4 - Reading the Joystick State
individual void UpdateFromGamePad()
{
// get the vector position of the left and right thumbstick
float transx = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X;
bladder transy = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.Y;
float rotx = GamePad.GetState(PlayerIndex.Ane).ThumbSticks.Right.X;
float roty = GamePad.GetState(PlayerIndex.1).ThumbSticks.Correct.Y;
// test to see if we are rotating with the right thumbstick
if ( (int)(rotx + .5f) == 1)
_ship.Update(0, 0, .01f);
if ((int)(rotx + -.5f) == -1)
_ship.Update(0, 0, -.01f);
// test to run into if we are moving with the left thumbstick
if ((int)(transx + .5f) == 1)
{
_ship.Update(one, 0, 0);
}
if ((int)(transx + -.5f) == -i)
{
_ship.Update(-1, 0, 0);
}
// see if nosotros are firing a photon torpedo. if we are then gear up the firing state
if (GamePad.GetState(PlayerIndex.I).Buttons.LeftShoulder == ButtonState.Pressed)
{
if (_weaponState == WeaponState.IDLE)
{
_photon.Position = new Vector2(_ship.Position.X, _ship.Position.Y);
_photon.Angle = _ship.Angle;
Audio.Play("photon_torpedo");
}
_weaponState = WeaponState.PHOTON_MOVING;
}
}
Drawing Fonts
Fonts are handled much in the same way as textures. Yous add together a SpriteFont to the content of your project. Y'all and so load the font using the ContentManager. Finally you depict the font in the Draw routine of your game object.
Start by correct clicking on your projection in solution explorer and choose, Add New Item. Choice the Sprite Font from the Content Dialog shown in effigy 2: Figure 2 Adding a new content Item This will produce an xml file that defines your font. Go into the content file and edit the file for the font parameters needed to customize the appearance of your font. In our case, nosotros changed the font to Arial Italic, size 24 as shown in list 5.
Listing 5 - Editing the Sprite Font Content File
<? xml version = "1.0" encoding ="utf-8"?> <!--
This file contains an xml clarification of a font, and will exist read by the XNA
Framework Content Pipeline. Follow the comments to customize the advent
of the font in your game, and to change the characters which are bachelor to draw
with.
-->
< XnaContent xmlns:Graphics = "Microsoft.Xna.Framework.Content.Pipeline.Graphics">
< Asset Type = "Graphics:FontDescription">
<!--
Alter this string to change the font that will be imported. Redistributable sample
fonts are available at http://get.microsoft.com/fwlink/?LinkId=104778&clcid=0x409.
-->
< FontName > Arial</ FontName >
<!--
Size is a bladder value, measured in points. Change this value to alter
the size of the font.
-->
< Size > 24</ Size >
<!--
Spacing is a bladder value, measured in pixels. Change this value to alter
the amount of spacing in between characters.
-->
< Spacing > 0</ Spacing >
<!--
UseKerning controls the layout of the font. If this value is truthful, kerning data
will be used when placing characters.
-->
< UseKerning > true</ UseKerning >
<!--
Mode controls the style of the font. Valid entries are "Regular", "Assuming", "Italic",
and "Bold, Italic", and are case sensitive.
-->
< Manner > Italic</ Mode >
<!--
CharacterRegions command what letters are available in the font. Every
character from Start to End will be congenital and made available for drawing. The
default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
character set. The characters are ordered according to the Unicode standard.
See the documentation for more information.
-->
< CharacterRegions >
< CharacterRegion >
< Starting time >   </ First >
< Stop > ~ </ End >
</ CharacterRegion >
</ CharacterRegions >
</ Asset >
</ XnaContent >
In one case we have a SpriteFont defined and added to our projection, we can load the font. Nosotros just call Load on the ContentManager object with the path of our font. In our example, we chose to put the font into a Font folder to better organize our project, so the path for the font becomes Content\Fonts\StarTrekFont every bit shown in listing 6. You can decide the name of your asset, by clicking on the SpriteFont in your projection and looking at the Nugget Name. In this instance, our Asset is called StarTrekFont.
Listing 6 - Loading the font into the game
SpriteFont _font;
/// <summary>
/// Load your graphics content. If loadAllContent is truthful, you should
/// load content from both ResourceManagementMode pools. Otherwise, just
/// load ResourceManagementMode.Manual content.
/// </summary>
/// <param proper name="loadAllContent"> Which type of content to load. </param>
protected override void LoadGraphicsContent(bool loadAllContent)
{
if (loadAllContent)
{
_font = content.Load<SpriteFont>(@"Content\Fonts\StarTrekFont");
...
Once the font is loaded, it is ready to depict. Nosotros draw the font in the Depict method provided by the Game class. We brandish the font by calling the DrawString method on the SpriteBatch class. This method allows us to position and color our font as we render it to the screen:
Listing 7 - Rendering the Font to the screen
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime"> Provides a snapshot of timing values. </param>
protected override void Depict(GameTime gameTime)
{
graphics.GraphicsDevice.Articulate(Color.Black);
DrawBackground();
_spriteBatch.Begin();
_spriteBatch.DrawString(_font, "Star Trek", new Vector2(550, 550), Color.Aquamarine);
_spriteBatch.Terminate();
...
Conclusion
Adding 3D Objects to your game is a adequately uncomplicated process once you are comfy working in the 3D coordinate organization. You tin can experiment with different textures on the sphere to get dissimilar types of planets. Likewise demonstrated in this article was employ of the joystick and drawing of fonts to a game. Stay tuned for our next XNA article for additional game functionality and improvements to Star Trek.
Source: https://www.c-sharpcorner.com/article/star-trek-part-ii-adding-moving-3d-objects-to-your-xna-g/
0 Response to "draw 2d string in 3d space xna"
Post a Comment