I know you can get the width and height of class Texture2d, but why can't you get the x and y coordinates? Do I have to create separate variables for them or something? Seems like a lot of work.
You must use a Vector2-object in association with a Texture2D-object. A Texture2D-object itself does not have any coordinates.
When you want to draw a texture, you will need a SpriteBatch to draw it, whereas this takes a Vector2D to determine the coordinates.
public void Draw (
Texture2D texture,
Vector2 position,
Color color
)
This is taken from MSDN.
So, either create a struct
struct VecTex{
Vector2 Vec;
Texture2D Tex;
}
or a class when you need further processing.
A Texture2D object alone doesn't have any screen x and y coordinates.
In order to draw a texture on the screen, you must either set it's position by using a Vector2 or a Rectangle.
Here's an example using Vector2:
private SpriteBatch spriteBatch;
private Texture2D myTexture;
private Vector2 position;
// (...)
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load the Texture2D object from the asset named "myTexture"
myTexture = Content.Load<Texture2D>(#"myTexture");
// Set the position to coordinates x: 100, y: 100
position = new Vector2(100, 100);
}
protected override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
spriteBatch.Draw(myTexture, position, Color.White);
spriteBatch.End();
}
And here's an example using Rectangle:
private SpriteBatch spriteBatch;
private Texture2D myTexture;
private Rectangle destinationRectangle;
// (...)
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load the Texture2D object from the asset named "myTexture"
myTexture = Content.Load<Texture2D>(#"myTexture");
// Set the destination Rectangle to coordinates x: 100, y: 100 and having
// exactly the same width and height of the texture
destinationRectangle = new Rectangle(100, 100,
myTexture.Width, myTexture.Height);
}
protected override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
spriteBatch.Draw(myTexture, destinationRectangle, null, Color.White);
spriteBatch.End();
}
The main difference is that by using a Rectangle you are able to scale your texture to fit the destination rectangle's width and height.
You can find some more information about the SpriteBatch.Draw method at MSDN.
Related
I'm working with XNA and a have a problem.
A basic problem, but argh !!!
I want to draw a ocean, BASIC ocean, just a plane, blue and transparent.
just a plane.
I have try with Vertex, with models and textures.
How tha alpha channel work in XNA ? StencilState, DepthBuffer, nothing would work.
Can you explain how to do this ?
Use VertexPositionColor enough ?
Excuse me, but I am looking for a long time.
class Ocean
{
Effect shader0;
public Vector3 Position;
GraphicsDevice Graphics;
Camera camera;
Model Mesh;
Texture2D waterTexture;
Rectangle screen;
Texture2D test;
public Ocean(Vector3 pos, int size, GraphicsDevice gra, Camera cam, ContentManager content)
{
Graphics = gra;
shader0 = content.Load<Effect>("Ocean");
//shader0 = new BasicEffect(this.Graphics);
waterTexture = content.Load<Texture2D>("Images/shaderUnderwater");
screen = new Rectangle(0, 0, this.Graphics.Viewport.Width, this.Graphics.Viewport.Height);
Position = pos;
Mesh = content.Load<Model>("Models/ocean");
camera = cam;
foreach (ModelMesh mesh in this.Mesh.Meshes)
{
foreach (ModelMeshPart part in mesh.MeshParts)
{
part.Effect = shader0;
}
}
}
bool underWater;
Vector3 lightDirection = new Vector3(-1.0f, -1.0f, -1.0f);
public void Draw(SpriteBatch spriteBatch, Player player)
{
Matrix world = Matrix.CreateScale(100f) * Matrix.CreateRotationX(MathHelper.ToRadians(-90f)) * Matrix.CreateTranslation(Position);
//this.shader0.EnableDefaultLighting();
this.shader0.Parameters["World"].SetValue(world);
this.shader0.Parameters["View"].SetValue(player.Camera.View);
this.shader0.Parameters["Projection"].SetValue(player.Camera.Projection);
// Dessin du model
foreach (ModelMesh mesh in this.Mesh.Meshes)
{
foreach (Effect effect in mesh.Effects)
{
effect.CurrentTechnique = effect.Techniques["Textured"];
effect.Parameters["DiffuseColor"].SetValue(new Vector4(1f, 0.2f, 0.2f, 1f) ); // a reddish light
effect.Parameters["DiffuseLightDirection"].SetValue(new Vector3(1, 0, 0) ); // coming along the x-axis
effect.Parameters["SpecularColor"].SetValue(new Vector4(0, 1, 0 ,1f) ); // with green highlights
effect.Parameters["World"].SetValue(world);
effect.Parameters["View"].SetValue(player.Camera.View);
effect.Parameters["Projection"].SetValue(player.Camera.Projection);
}
mesh.Draw();
}
this.Graphics.BlendState = BlendState.Opaque;
//Effet
if (camera.Position.Y < Position.Y)
spriteBatch.Draw(this.waterTexture, this.screen, Color.White);
}
public void Update(GameTime gameTime)
{
}
void onWater()
{
underWater = true;
}
}
}
If you are using the BasicEffect to render the ocean, then BasicEffect has an Alpha property, which affects the transparency. Please see here: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.basiceffect.alpha.aspx
You can use BasicEffect to create transparency with any way that you are using for rendering your model.
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
namespace TileEngine
{
class Renderer : DrawableGameComponent
{
SpriteBatch spriteBatch;
public Renderer(Game game)
: base(game)
{
// TODO: Construct any child components here
}
protected override void LoadContent()
{
// base.LoadContent();
}
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
public override void Initialize()
{
base.Initialize();
}
public RenderTarget2D new_texture(int width, int height)
{
Texture2D TEX = new Texture2D(GraphicsDevice, width, height); //create the texture to render to
RenderTarget2D Mine = new RenderTarget2D(GraphicsDevice, width, height);
GraphicsDevice.SetRenderTarget(Mine); //set the render device to the reference provided
//maybe base.draw can be used with spritebatch. Idk. We'll see if the order of operation
//works out. Wish I could call base.draw here.
return Mine; //I'm hoping that this returns the same instance and not a copy.
}
public void draw_texture(int width, int height, RenderTarget2D Mine)
{
GraphicsDevice.SetRenderTarget(null); //Set the renderer to render to the backbuffer again
Rectangle drawrect = new Rectangle(0, 0, width, height); //Set the rendering size to what we want
spriteBatch.Begin(); //This uses spritebatch to draw the texture directly to the screen
spriteBatch.Draw(Mine, drawrect, Color.White); //This uses the color white
spriteBatch.End(); //ends the spritebatch
//Call base.draw after this since it doesn't seem to recognize inside the function
//maybe base.draw can be used with spritebatch. Idk. We'll see if the order of operation
//works out. Wish I could call base.draw here.
}
public GraphicsDevice myDevice { get; set; }
}
}
I still can't call this class as an object in XNA
Here is the working code in the initialize function where I try to create it.
But in my draw code it still doesn't let me go:
tileclipping.draw_texture(...);
Here's the full code from game1
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using TileEngine;
namespace TileEngine
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
public GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
TileMap myMap = new TileMap();
int squaresAcross = 12;
int squaresDown = 12;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// tileClipping = new Renderer();
// TODO: Add your initialization logic here
Renderer tileclipping = new Renderer(this) ;
//Components.Add(tileclippping);
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
Tile.TileSetTexture = Content.Load<Texture2D>(#"Textures\TileSets\part1_tileset");
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
KeyboardState ks = Keyboard.GetState();
if (ks.IsKeyDown(Keys.Left))
{
Camera.Location.X = MathHelper.Clamp(Camera.Location.X - 8, 0, (myMap.MapWidth - squaresAcross) * 32);
}
if (ks.IsKeyDown(Keys.Right))
{
Camera.Location.X = MathHelper.Clamp(Camera.Location.X + 8, 0, (myMap.MapWidth - squaresAcross) * 32);
}
if (ks.IsKeyDown(Keys.Up))
{
Camera.Location.Y = MathHelper.Clamp(Camera.Location.Y - 8, 0, (myMap.MapHeight - squaresDown) * 32);
}
if (ks.IsKeyDown(Keys.Down))
{
Camera.Location.Y = MathHelper.Clamp(Camera.Location.Y + 8, 0, (myMap.MapHeight - squaresDown) * 32);
}
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
//use the instance of renderer called tileclipping to generate a new texture of a specified size for tiles
//this surface is 200 pixels by 200 pixels for the reason that it's the same as the clipping i'll choose
Texture2D mytexture = new Texture2D(GraphicsDevice, 200, 200);
RenderTarget2D Mine = new RenderTarget2D(graphics.GraphicsDevice, 200, 200);
//Mine = tileclipping.new_texture(200, 200);
spriteBatch.Begin();
Vector2 firstSquare = new Vector2(Camera.Location.X / 32, Camera.Location.Y / 32);
int firstX = (int)firstSquare.X;
int firstY = (int)firstSquare.Y;
Vector2 squareOffset = new Vector2(Camera.Location.X % 32, Camera.Location.Y % 32);
int offsetX = (int)squareOffset.X;
int offsetY = (int)squareOffset.Y;
for (int y = 0; y < squaresDown; y++)
{
for (int x = 0; x < squaresAcross; x++)
{
spriteBatch.Draw(
Tile.TileSetTexture,
new Rectangle((x * 32) - offsetX, (y * 32) - offsetY, 32, 32),
Tile.GetSourceRectangle(myMap.Rows[y + firstY].Columns[x + firstX].TileID),
Color.White);
}
}
spriteBatch.End();
// TODO: Add your drawing code here
//There are two instances of mine
//A new one is made each time tileclipping.new_texture is called
//This function can re use the copy created by new texture
//hopefully this saves on memory
base.Draw(gameTime);
}
public CubeMapFace Tex2d { get; set; }
internal Renderer tileClipping { get; set; }
public IGameComponent tileclippping { get; set; }
}
}
I'm sorry if it isn't clear what i'm trying to do.
I'm trying to capture a 2d texture (or create one) OUTSIDE my game class
I'm trying to use a class as a handler, to pass these texture2d's back and forth between GAME1
and my Renderer
I don't WANT to have all my textures inside my main class.
Also another thing with this is that I'm trying to basically have a generic
texture2d CREATOR.
Aka this isn't for something simple like rendering sprites.
The function of RENDERER is to either create a new TEXTURE2D object with a NEW render target object
based on parameters fed to this function:
public RenderTarget2D new_texture(int width, int height)
{
Texture2D TEX = new Texture2D(GraphicsDevice, width, height); //create the texture to render to
RenderTarget2D Mine = new RenderTarget2D(GraphicsDevice, width, height);
GraphicsDevice.SetRenderTarget(Mine); //set the render device to the reference provided
//maybe base.draw can be used with spritebatch. Idk. We'll see if the order of operation
//works out. Wish I could call base.draw here.
return Mine; //I'm hoping that this returns the same instance and not a copy.
}
I need a way of creating a copy of the renderer class WITHOUT having it in the gamecomponents list.
The reason is because XNA won't let me access Graphics device, which is a required parameter OF a texture2D object.
So basically i'm doing all this stuff as a work around just becuase Texture2D requires graphics device as a parameter and I can't willy nilly pass GraphicsDevice INTO an instance of my renderer class i've already tried that and it fails.
So there will be situations in my game where say
if (Camera_zoom==1){
scaling_texture.dispose();
scaling_texture = tileclipping.new_texture(camera_width*camera_zoom, camera_height*camera_zoom);
// call a refresh command here
this.refresh_scene(...) //Inside here is a ton of sprite batches because the render target is now set to NEW scaling_texture
//after that we do the drawing using spritebatch inside draw function of main game class
//expecting that a render texture is provided for us by these pre requisites.
//then after that we call the render command
//it returns the render target to the screen
//then in the draw command AFTER the sprite batches were drawn TO the target surface called scaling_texture
//We use various parameters to tell it to draw this scaling_texture as a spritebatch.draw() inside the
//game1 draw class
//So basically I want to do things in this order
/// Create new texture of variable size
// use it as render target
// Do all my spritebatch
// call another spritebatch
//draw the contents of said texture on the screen as the rendering target
//Dispose of the texture object
//Check the scaling size of it
//Re create the scaling texture with a NEW resolution (each frame)
//Select it as a render target
//Do the spritebatchy stuff all over again repeat above for all game loop
//BUT I want parts of this, mainly the creation of this Texture2D object, and the drawing of it to the backbuffer
//To all happen inside my Renderer class
//but for all main game spritebatches to happen inside my main game class
//This is a problem for me and XNA doesn't seem to want to let me organize it this way
//Unless i'm missing something which is why i'm making this lengthy post
//ANY and all help is appreciated.
//Thanks again and I hope I explained myself well enough this time IE my intentions.
//PLEASE NOTE I am SET on doing things THIS way. I will NEED a texture 2d rendering target that is NON static
//During MOST of my GAME project.
//That said.. IT HAS TO have function to wrap it inside Renderer. THere is no way in hell I'm going to do this
//In a spaghetti code fashion Inside GAME1 with nested if statements.
//Thanks all
}
I just took the time to read it completely, and if I understand correctly, you want to have all your textures into a manager to be able to acess them from everywhere in your program ?
what I normally do is have a Class like this one :
Class Images
{
public static Texture2d Ball;
public static Texture2d Hero;
public static void loadContent(Content content)
{
Ball = content.load<Texture2d>("/GFX/GameObject/Ball");
Hero = content.load<Texture2d>("/GFX/SpriteSheet/Hero");
}
}
This class allow you to use Image.Hero or Image.Ball from everywhere in your code. All you have to do is to set it in your game loadcontent sub :
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
Images.LoadContent(GraphicsDeviceManager.Content);
Sounds.LoadContent(GraphicsDeviceManager.Content);
Tile.TileSetTexture = Content.Load<Texture2D>(#"Textures\TileSets\part1_tileset");
// TODO: use this.Content to load your game content here
}
From here, if you need to recreate or reload the texture in your own renderer class, you could set images.ball getter or setter differently and handle it how you want, or just create a new function to clone these texture and do what you need for your renderer class. Edit : I'm not 100% sure about if the class itself is static or not, I dont have the code in front of me and I didnt touch it in a long time.
I'm not home, so I cant find the tutorial I had about splash screen. but it also let you load a delegate instead of an asset, and that delegate lets you do some actions instead : as the 1st item to load, you load all the texture and fonts needed for your splash screen, as well as a background music that you start playing right away. If you want, let me know and I'll add in the link once I get home.
I created a model in Blender and then I used armature to create some pose. How can I display this pose in XNA/MonoGame? I can't find any solution. I use model exported to fbx file.
My only code is here and it draws model without armature effect:
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
// Copy any parent transforms.
Matrix[] transforms = new Matrix[myModel.Bones.Count];
myModel.CopyAbsoluteBoneTransformsTo(transforms);
// Draw the model. A model can have multiple meshes, so loop.
foreach (ModelMesh mesh in myModel.Meshes)
{
// This is where the mesh orientation is set, as well as our camera and projection.
foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationY(modelRotation)
* Matrix.CreateTranslation(modelPosition);
effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
aspectRatio, 1.0f, 10000.0f);
}
// Draw the mesh, using the effects set above.
mesh.Draw();
}
base.Draw(gameTime);
}
I would like to make a simple thing in XNA where the background would move when the character moves to the right.
Any ideas how to do it?
thanks
I think you mean like in the game Mario!
Using Scrolling.
Create the game class.
Load resources as described in the procedures of Drawing a Sprite.
Load the background texture.
private ScrollingBackground myBackground;
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
myBackground = new ScrollingBackground();
Texture2D background = Content.Load<Texture2D>("starfield");
myBackground.Load(GraphicsDevice, background);
}
Determine the size of the background texture and the size of the screen.
The texture size is determined using the Height and Width properties, and the screen size is determined using the Viewport property on the graphics device.
Using the texture and screen information, set the origin of the texture to the center of the top edge of the texture, and the initial screen position to the center of the screen.
// class ScrollingBackground
private Vector2 screenpos, origin, texturesize;
private Texture2D mytexture;
private int screenheight;
public void Load( GraphicsDevice device, Texture2D backgroundTexture )
{
mytexture = backgroundTexture;
screenheight = device.Viewport.Height;
int screenwidth = device.Viewport.Width;
// Set the origin so that we're drawing from the
// center of the top edge.
origin = new Vector2( mytexture.Width / 2, 0 );
// Set the screen position to the center of the screen.
screenpos = new Vector2( screenwidth / 2, screenheight / 2 );
// Offset to draw the second texture, when necessary.
texturesize = new Vector2( 0, mytexture.Height );
}
To scroll the background, change the screen position of the background texture in your Update method.
This example moves the background down 100 pixels per second by increasing the screen position's Y value.
protected override void Update(GameTime gameTime)
{
...
// The time since Update was called last.
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
// TODO: Add your game logic here.
myBackground.Update(elapsed * 100);
base.Update(gameTime);
}
The Y value is kept no larger than the texture height, making the background scroll from the bottom of the screen back to the top.
public void Update( float deltaY )
{
screenpos.Y += deltaY;
screenpos.Y = screenpos.Y % mytexture.Height;
}
// ScrollingBackground.Draw
Draw the background using the origin and screen position calculated in LoadContent and Update.
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
myBackground.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
In case the texture doesn't cover the screen, another texture is drawn. This subtracts the texture height from the screen position using the texturesize vector created at load time. This creates the illusion of a loop.
public void Draw( SpriteBatch batch )
{
// Draw the texture, if it is still onscreen.
if (screenpos.Y < screenheight)
{
batch.Draw( mytexture, screenpos, null,
Color.White, 0, origin, 1, SpriteEffects.None, 0f );
}
// Draw the texture a second time, behind the first,
// to create the scrolling illusion.
batch.Draw( mytexture, screenpos - texturesize, null,
Color.White, 0, origin, 1, SpriteEffects.None, 0f );
}
Why Vector2 (from XNA's library) uses float not int?
Position on computer screen is given in pixels so that cursor position can be defined by two integers. There is no such a thing like half a pixel. Why we use floats then?
In SpriteBatch class I've found 7 overloaded methods called Draw. Two of them:
public void Draw(Texture2D texture, Rectangle destinationRectangle, Color color);
public void Draw(Texture2D texture, Vector2 position, Color color);
So we can see that Draw accepts both int and float coordinates.
I came across this problem when I've been implementing screen coordinates of my game's objects. I assumed that Rectangle is good choice to hold object's size and screen coordinates. But now I'm not sure...
Mathematically, a vector is a motion, not a position. While a position on the screen might not technically be able to be between integers, a motion definitely can. If a vector used ints then the slowest you could move would be (1, 1). With floats you can move (.1, .1), (.001, .001), and so on.
(Notice also that the XNA struct Point does actually use ints.)
You could use both Vector2 and Rectangle to represent your objects coordinates. I usually do it like this:
public class GameObject
{
Texture2D _texture;
public Vector2 Position { get; set; }
public int Width { get; private set; } //doesn't have to be private
public int Height { get; private set; } //but it's nicer when it doesn't change :)
public Rectangle PositionRectangle
{
get
{
return new Rectangle((int)Position.X, (int)Position.Y, Width, Height);
}
}
public GameObject(Texture2D texture)
{
this._texture = texture;
this.Width = texture.Width;
this.Height = texture.Height;
}
}
To move objects, just set their Position property to a new value.
_player.Position = new Vector2(_player.Position.X, 100);
You don't have to worry about the rectangle, as it's value depends directly on Position.
My game objects also usually contain methods to draw themselves, such as
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
spriteBatch.Draw(this._texture, this.Position, Color.White);
}
Collision detection code in your Game.Update() could just use the PositionRectangle to test for collisions
//_player and _enemy are of type GameObject (or one that inherits it)
if(_player.PositionRectangle.Intersects(_enemy.PositionRectangle))
{
_player.Lives--;
_player.InvurnerabilityPeriod = 2000;
//or something along these lines;
}
You could also call the spriteBatch.Draw() with PositionRectangle, you shouldn't notice much difference.
There is such a thing as "half a pixel." Using float coordinates that aren't pixel-aligned will cause your sprites to be rendered at sub-pixel coordinates. This is often necessary to make objects appear to scroll smoothly, but it can also produce an unpleasant shimmering effect in some circumstances.
See here for a summary of the basic idea: Subpixel rendering