Wednesday, March 14, 2012

Tutorial-Draw A Line At XNA(Window Phone)

如果沒有使用 DrawPrimitive Methods做的話,XNA 並無提供簡單產生出一個線段,因此在這裡提供一下簡易 2D線段的方法。

 


The XNA dosen’t provide a way to Draw a Line if you don’t use 3D DrawPrimitive Methods

 

image


第一步:
產生一個 1X1 Texture。
產生下列Code


Texture2D pixel;
Vector2 firstPosition;
Vector2 secondPosition;
float rotation;
float length;
//At LoadContet Method
protected override void LoadContent()
{

..
pixel = Content.Load<Texture>("Your Texture Location");
..
base.Initialize();
}
現在我們要選擇兩個點去產生線段,我們必須算出角度和長度來決定線段
protected override void Draw(GameTime gameTime)
{
...
distance = Vector2.Distance(secondPosition,firstPosition);
rotation = (float)Math.Atan2(secondPosition.Y - firstPosition.Y,secondPosition.X - firstPosition.X);
spriteBatch.Begin();
spriteBatch.Draw(pixel,firstPosition,null,Color.Black,rotation,Vector2.Zero,new Vector2(distance,5),SpriteEffects.None,0);
spriteBatch.End();
...
}
這樣大致在XNA上完成畫線動作了,windowPhone可以使用GestureSample是取的tap的位置 firstPosition 和 secondPosition位置。
--------------------------------------------------------------------------------------------------------------------------------
That’s Begin
Create a 1x1 Texture
And Coding
Texture2D pixel;
Vector2 firstPosition;
Vector2 secondPosition;
float rotation;
float length;
//At LoadContet Method
protected override void LoadContent()
{
..
pixel = Content.Load<Texture>("Your Texture Location");
..
base.Initialize();
}
We need to know length between firstPosition and secondPosition.
And caculatr Rotation angle between firstPosition and secondPosition.
protected override void Draw(GameTime gameTime)
{
...
distance = Vector2.Distance(secondPosition,firstPosition);
rotation = (float)Math.Atan2(secondPosition.Y - firstPosition.Y,secondPosition.X - firstPosition.X);
spriteBatch.Begin();
spriteBatch.Draw(pixel,firstPosition,null,Color.Black,rotation,Vector2.Zero,new Vector2(distance,5),SpriteEffects.None,0);
spriteBatch.End();
...
}
And see result is Perfect.
if you want do in Window Phone then you can use GestureSample 's GestureType.Tap to make two postion to create a line.

No comments:

Post a Comment