Sunday, January 20, 2019

xna 4.0 - Drawing a texture line between two vectors in XNA WP7


I want to create a simple graph maker in WP7.


The goal is to draw a texture line between two vectors what the user defines with touch. I already made the rotation, and it is working, but not correctly, because it doesn't calculate the line's texture height, and because of that, there are too many overlapping textures. So it does draw the line, but too many of them.


How could I calculate it correctly?


Here is the code:


public void DrawLine(Vector2 st,Vector2 dest,NodeUnit EdgeParent,NodeUnit EdgeChild)

{
float d = Vector2.Distance(st, dest);
float rotate = (float)(Math.Atan2(st.Y - dest.Y, st.X - dest.X));
direction = new Vector2(((dest.X - st.X) / (float)d), (dest.Y - st.Y) / (float)d);
Vector2 _pos = st;
World.TheHive.Add(new LineHiveMind(linetexture, _pos, rotate, EdgeParent, EdgeChild,new List()));
for (int i = 0; i < d; i++)
{
World.TheHive.Last()._lines.Add(new LineUnit(linetexture, _pos, rotate, EdgeParent, EdgeChild));
_pos += direction;


}
}


  • d is for the Distance of the st (Starting node) and dest (Destination node)

  • rotate is for rotation

  • direction calculates the direction between the starting and the destination node

  • _pos is for starting position changing



Thanks for any suggestions/help!



Answer



I'm not sure I understood what your problem is, but here's how I do it. First I create a static class on my project to provide an extension method for SpriteBatch that lets it know how to draw textured line. Example (just the class, it's missing the using directives and the namespace so place it wherever you want):


public static class LineRenderer
{
public static void DrawLine(this SpriteBatch spriteBatch, Texture2D texture, Vector2 start, Vector2 end)
{
spriteBatch.Draw(texture, start, null, Color.White,
(float)Math.Atan2(end.Y - start.Y, end.X - start.X),
new Vector2(0f, (float)texture.Height / 2),

new Vector2(Vector2.Distance(start, end), 1f),
SpriteEffects.None, 0f);
}
}

The texture passed to the method should have size 1xN where N is the thickness of my ine. I'll give an example further below but first an usage example:


spriteBatch.Begin();
spriteBatch.DrawLine(lineTexture, new Vector2(20, 20), new Vector2(120, 120));
spriteBatch.DrawLine(lineTexture, new Vector2(120, 20), new Vector2(220, 60));
spriteBatch.DrawLine(lineTexture, new Vector2(20, 240), new Vector2(220, 100));

spriteBatch.End();

Which gives the following result (using the texture on the right side which I zoomed in for clarity):


enter image description here


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...