Moving sprite on the screen in XNA

Because you work directly with screen coordinates when creating 2D games, moving a sprite is simple. All you need to do is draw the sprite in a different position. By incrementing the x coordinate of the sprite position, the sprite moves to the right; by decrementing, you move the sprite to the left. If you want to move the sprite down on the screen, you need to increment the y coordinate.
You move the sprite up by decrementing the y coordinate. Keep in mind that the (0, 0) point in screen coordinates is the upper-left corner of the window.
The XNA Framework basic game project provides a specific place to do the game calculations:

You can move the sprite by simply adding one line in the code, incrementing the X position of the sprite, according to the following line of code:
mySprite1.position.X += 1;
Because you use the sprite’s position property when rendering the sprite in the Draw method, by including this line, you’ll be able to see the sprite moving across the window, to the right, until it disappears from the screen.

To create a more game-like sprite, let’s do something a little more sophisticated. First, create a new property in the clsSprite class, velocity, that defines the sprite velocity on both the x and y axes. Then modify the class constructor to receive and store the screen coordinates, so you can include a method that moves the sprite according to the given velocity, which doesn’t let the sprite move off the screen.
To begin, delete the code line that changes the X position of the sprite. Next, modify the sprite class constructor, and change the sprite creation code in the Game1 class. In the clsSprite.cs file, make the following adjustment to the class constructor:

private Vector2 screenSize { get; set; } // Screen size
public clsSprite (Texture2D newTexture, Vector2 newPosition,
Vector2 newSize, int ScreenWidth, int ScreenHeight)
{
texture = newTexture;
position = newPosition;
size = newSize;
screenSize = new Vector2(ScreenWidth, ScreenHeight);
}

Change the sprite-creation code accordingly in the Game1.cs file, in the LoadContent method:

mySprite1 = new clsSprite(Content.Load("xna_thumbnail"),
new Vector2(0f, 0f), new Vector2(64f, 64f),
graphics.PreferredBackBufferWidth,
graphics.PreferredBackBufferHeight);
Create a new property in the sprite class, velocity:
public Vector2 velocity { get; set; } // Sprite velocity

Set this velocity to (1,1) in the LoadContent method, after the sprite-creation code, so you’ll inform the sprite that it should move one pixel per update on both the x and y axes. This way, the sprite will move diagonally across the screen.
mySprite1.velocity = new Vector2(1, 1);
You have the screen bounds, and you have the speed. Now you need to create a method let’s call it Move in the sprite class that moves the sprite according to the sprite velocity, respecting the screen boundaries. The code for this method follows:

public void Move()
{
// If we'll move out of the screen, invert velocity
// Checking right boundary
if (position.X + size.X + velocity.X > screenSize.X)
velocity = new Vector2(-velocity.X, velocity.Y);
// Checking bottom boundary
if (position.Y + size.Y + velocity.Y > screenSize.Y)
velocity = new Vector2(velocity.X, -velocity.Y);
// Checking left boundary
if (position.X + velocity.X < 0)
velocity = new Vector2(-velocity.X, velocity.Y);
// Checking upper boundary
if (position.Y + velocity.Y < 0)
velocity = new Vector2(velocity.X, -velocity.Y);
// Since we adjusted the velocity, just add it to the current position
position += velocity;
}

Because Vector2 classes represent both the sprite position and velocity, you could simply add the vectors to change the sprite position. However, because you don’t want to add the velocity if it will take the sprite off the screen, you include code to invert the velocity in this situation.
Checking for left and top screen boundaries is a direct test, because the sprite position is given by its upper-left corner. However, when checking if the sprite will leave the screen on the right, you must add the sprite width to the sprite’s X position to make the sprite bounce with its right corner, or it would leave the screen before bouncing back. Similarly, when checking if the sprite is leaving through the bottom of the screen, you must add the sprite height to its Y position
so the sprite will bounce with its bottom.

As a final step, include the call to the sprite’s Move method in the Update method of the Game1.cs class:
mySprite1.Move();
Read the code carefully to be sure you understand the tests, and then run the code. The sprite will move across the screen and bounce against the window borders!

Texture Drawing in XNA

Because XNA 2D programming is almost entirely a process of moving sprites around the screen, you might expect that loading and drawing bitmaps in an XNA program is fairly easy, and you would be correct.
The first project is called XnaLocalBitmap, so named because this bitmap will be stored as part of the program’s content. To add a new bitmap to the program’s content project, right-click the XnaLocalBitmapContent project name, select Add and then New Item, and then Bitmap File. You can create the bitmap right in Visual Studio.

To add this file as part of the program’s content, right-click the XnaLocalBitmapContent project in Visual Studio, select Add and Existing Item, and then navigate to the file. Once the file shows up, you can right-click it to display Properties, and you’ll see that it has an Asset Name of “Hello.”
The goal is to display this bitmap centered on the screen. Define a field in the Game1.cs file to store the Texture2D and another field for the position:

public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D helloTexture;
Vector2 position;
...
}

Both fields are set during the LoadContent method. Use the same generic method to load the Texture2D as you use to load a SpriteFont. The Texture2D class has properties named Width and Height that provide the dimensions of the bitmap in pixels.

protected override void LoadContent()
{
spriteBatch = new SpriteBatch ( GraphicsDevice );
helloTexture = this.Content.Load <Texture2D> ("Hello");
Viewport viewport = this.GraphicsDevice.Viewport;
position = new Vector2 (  (viewport.Width - helloTexture.Width  ) / 2,
(viewport.Height - helloTexture.Height) / 2);
}

The SpriteBatch class has seven Draw methods to render bitmaps. This one is certainly the simplest:

protected override void Draw (GameTime gameTime)
{
GraphicsDevice.Clear ( Color.Navy );
spriteBatch.Begin ();
spriteBatch.Draw ( helloTexture, position, Color.White );
spriteBatch.End ();
base.Draw ( gameTime );
}

The final argument to Draw is a color that can be used to attenuate the existing colors in the bitmap. Use Color.White if you want the bitmap’s colors to display without any alteration.

Creating a Split Screen with XNA

To create a split screen, we need to two different viewports. We have only been using one up until now and we actually retrieved it in our camera’s Initialization method. We simply grabbed the GraphicsDevice.Viewport property to get our camera’s viewport.
Because we want to display two screens in one we need to define our two new viewports and then let the cameras (we will need two cameras) know about them so we can get the desired effect.
Because we want to display two screens in one we need to define our two new viewports and then let the cameras (we will need two cameras) know about them so we can get the desired effect. To start we will need to add the following private member fields to our Game1.cs code:

private Viewport defaultViewport;
private Viewport topViewport;
private Viewport bottomViewport;
private separatorViewport;
private bool twoPlayers = true;
private FirstPersonCamera camera2;
Then at the end of our LoadGraphicsContent method we will need to define those viewports
and create our cameras and pass the new values. We do this in the following code:
if (twoPlayers)
{
defaultViewport = graphics.GraphicsDevice.Viewport;
topViewport = defaultViewport;
bottomViewport = defaultViewport;
topViewport.Height = topViewport.Height / 2;
separatorViewport.Y = topViewport.Height – 1;
separatorViewport.Height = 3;
bottomViewport.Y = topViewport.Height + 1;
bottomViewport.Height = (bottomViewport.Height / 2) - 1;
camera.Viewport = topViewport;

camera2 = new FirstPersonCamera(this);
camera2.Viewport = bottomViewport;
camera2.Position = new Vector3(0.0f, 0.0f, -3.0f);
camera2.Orientation = new Vector3(0.0f, 0.0f, 1.0f);
camera2.PlayerIndex = PlayerIndex.Two;
Components.Add(camera2);
}

We discussed briefly that we would need more than one camera to pull this off. This is because we have our view and projection matrices associated with our camera class. It makes sense that we will have two cameras because the camera is showing what the player is seeing. Each player needs his or her own view into the game. Our initial camera is still set up in our game’s constructor but our second camera will get added here. Our first camera gets the default viewport associated with it. The first thing the preceding code is doing is checking to see if we are in a two-player game. For a real game, this should be determined by an options menu or something similar, but for now we have just initialized the value to true when we initialized the twoPlayer variable.

Inside of the two-player condition the first thing we do is set our default viewport to what we are currently using (the graphic device’s viewport). Then we set our top viewport to the same value. We also initialize our bottomViewport to our defaultViewport value. The final thing we do with our viewports is resize them to account for two players. We divide the height in two (we are making two horizontal viewports) on both. We then set our bottom viewport’s Y property to be one more than the height of our bottom. This effectively puts the bottom viewport right underneath our top viewport.
While still in the two-player condition we change our first camera’s viewport to use the top viewport. Then we set up our second camera by setting more properties. Not only do we set the viewport for this camera to the bottom viewport we have, but we also set a new camera position as well as the orientation of the camera. Finally, we set the player index. None of these properties is exposed from our camera object, so we need to open our Camera.cs file and make some changes to account for this. First, we need to add a new private member field to hold our player index. We just assumed it was player 1 before. We can set up our protected (so our FirstPersonCamera class can access it) index as an integer as follows:

protected int playerIndex = 0;

Now, we can actually modify our input code that controls our camera to use this index instead of the hard-coded value 0 for our game pads. In the camera’s Update method we can change any instance of input.GamePads[0] to input.GamePads[playerIndex]. We also need to do the same for the FirstPersonCamera object. We did not update the keyboard code and will not for the sake of time. However, to implement multiple users where both can use the keyboard we should create a mapping for each player and check accordingly.
In general, it is a good practice to have a keyboard mapping so that if gamers do not like the controls we have defined in our games then they have a way to change them so it works more logically for them. The same can be said about creating a mapping for the game pads but many games simply give a choice of a couple of layouts. Because the code does not implement a keyboard mapping, the only way for us to control the separate screens differently is by having two game pads hooked up to our PC or Xbox 360. After we have changed our camera to take the player index into consideration before reading values from our game pad, we can add the following properties to our code:

public PlayerIndex PlayerIndex
{
get { return ((PlayerIndex)playerIndex); }
set { playerIndex = (int)value; }
}
public Vector3 Position
{
get { return (cameraPosition); }
set { cameraPosition = value; }
}
public Vector3 Orientation
{
get { return (cameraReference); }
set { cameraReference = value; }
}
public Vector3 Target
{
get { return (cameraTarget); }
set { cameraTarget = value; }
}
public Viewport Viewport
{
get
{
if (viewport == null)
viewport = graphics.GraphicsDevice.Viewport;
return ((Viewport)viewport);
}
set
{
viewport = value;
InitializeCamera();
}
}

We are simply exposing the camera’s position, orientation (reference), and target variables. For the player index property we are casting it to a PlayerIndex enumeration type. The final property is the Viewport property. We first check to see if our viewport variable is null and if so we set it to the graphics device’s viewport. When we set our Viewport property, we also call our InitializeCamera method again so it can recalculate its view and projection matrices. We need to set up a private member field for our viewport. We will allow it to have a default null value so we can declare it as follows:
private Viewport? viewport;
Because we are utilizing the Viewport type we will need to add the following using statement to our code:
using Microsoft.Xna.Framework.Graphics;
The only thing left for us to do now is to actually update our game’s drawing code to draw our scene twice. Because we are going to have to draw our scene twice (once for each camera) we will need to refactor our Draw code into a DrawScene method and pass in a camera reference. Our new code for the new Draw method is as follows:

protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Viewport = camera.Viewport;
DrawScene(gameTime, camera);
if (twoPlayers)
{
graphics.GraphicsDevice.Viewport = camera2.Viewport;
DrawScene(gameTime, camera2);
//now clear the thick horizontal line between the two screens
graphics.GraphicsDevice.Viewport = separatorViewport;
graphics.GraphicsDevice.Clear(Color.Black);
}
base.Draw(gameTime);
}

We took all of the code that was inside of this method and put it into a new method DrawScene(GameTime gameTime, Camera camera). The code we put into the DrawScene method did not change from how it looked when it resided inside of the Draw method.
The first thing we do with the preceding code is set our graphics device’s viewport to be what our camera’s viewport is. We then draw the scene passing in our camera. Then we check to see if we have two players; if so we set the viewport appropriately and finally draw the scene for that camera. We can run our application and see that it is using a split screen.

Formula to Convert CMYK to RGB values

It is possible to convert CMYK values to RGB values. We can see how to do this in the following section.

Consider the cyan, magento, yellow and black values of CMYK as c, m, y and k respectively. Now we can find the equivalent RGB values using the following formulas :

r = (1-k)-(1-k)*c;

g = (1-k)-(1-k)*m;

b = (1-k)-(1-k)*y;

Here, r, g and b will have the corresponding red, green and blue values.

Setting polygon properties dynamically in WP7

Following code snippet will create polygon and set properties dynamically:

Polygon polygon = new Polygon;

polygon.Points = new PointCollection()
{

new Point(150, 50),
new Point(10, 50),
new Point(50, 20)
};
polygon.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue);
polygon.Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red);
polygon.StrokeThickness = 3;
polygon.Opacity = 0.5;

Dynamically creating polygon in windows phone 7

The following code snippet will create a polygon dynamically:


Polygon polygon = new Polygon();

..

polygon.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red);

polygon.Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Yellow);

polygon.StrokeThickness = 5;

polygon.Opacity = 0.4;
polygon.Points = new PointCollection()
{

new Point(150, 50),
new Point(10, 50),
new Point(50, 20)

};
grid.Children.Add(polygon);

That's it!

How to determine Windows Java installation location?

private string GetJavaInstallationPath()
{
    string environmentPath = Environment.GetEnvironmentVariable("JAVA_HOME");
    if (!string.IsNullOrEmpty(environmentPath))
    {
       return environmentPath;
    }

    string javaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
    using (Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(javaKey))
    {
        string currentVersion = rk.GetValue("CurrentVersion").ToString();
        using (Microsoft.Win32.RegistryKey key = rk.OpenSubKey(currentVersion))
        {
            return key.GetValue("JavaHome").ToString();
        }
    }
}

Then to use it, just do the following:
string installPath = GetJavaInstallationPath();
string filePath = System.IO.Path.Combine(installPath, "bin\\Java.exe");
if (System.IO.File.Exists(filePath))
{
    // We have a winner
}

Integrating Contact list to an app in windows phone

using Microsoft.Phone.UserData;

private void ButtonContacts_Click(object sender, RoutedEventArgs e)
{
    Contacts cons = new Contacts();

    //Identify the method that runs after the asynchronous search completes.
    cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);

    //Start the asynchronous search.
    cons.SearchAsync(String.Empty, FilterKind.None, "Contacts Test #1");
}

void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
    //Do something with the results.
    MessageBox.Show(e.Results.Count().ToString());
}