Creating a speedometer ,largely depends whether you want to display a numerical readout, or as a rotating needle.
First, to get the actual speed value, as mentioned in another answer, you can simply use the rigid body’s velocity. However, Unity’s default scale is one unit = one meter, so reading rigidbody.velocity.magnitude will give you the speed in meters per second.
To convert to MPH, you can use:
1: var mph = rigidbody.velocity.magnitude * 2.237;
Convert to KPH:
1: var kph = rigidbody.velocity.magnitude * 3.6;
Next to display it.
To show the speed as a numerical readout is comparitively simple:
1) Create a GUIText gameobject (from the gameobject menu).
2) In your car script, create a var which will store a reference to this GUIText GameObject:
1: var mphDisplay : GUIText;
3) Select your car, and drag a reference from the new GUIText GameObject in the hierarchy into this variable slot in car script, in the inspector.
4) Now, in your car script, you can add the lines in your Update() function to calculate the MPH, and update the text displayed:
1: var mph = rigidbody.velocity.magnitude * 2.237;
2: mphDisplay.text = mph + " MPH";
That should get you working with a numerical readout.
To display as a rotating needle requires some trickier coordination. There’s no simple way to rotate a GUI Texture, or a texture drawn using the OnGUI method, so I’ve written a small general-purpose script which you can place on a gameobject to create a rotatable GUI Texture. You can control it by setting the ‘angle’ variable from other scripts.
So:
1) Create a new C# script. Name it “RotatableGuiItem”, and paste in this script:
1: using UnityEngine;
2: [ExecuteInEditMode()]
3: publicclass RotatableGuiItem : MonoBehaviour {
4:
5: public Texture2D texture = null;
6: publicfloat angle = 0;
7: public Vector2 size = new Vector2(128, 128);
8: Vector2 pos = new Vector2(0, 0);
9: Rect rect;
10: Vector2 pivot;
11:
12: void Start() {
13: UpdateSettings();
14: }
15:
16: void UpdateSettings() {
17: pos = new Vector2(transform.localPosition.x, transform.localPosition.y);
18: rect = new Rect(pos.x - size.x * 0.5f, pos.y - size.y * 0.5f, size.x, size.y);
23: if (Application.isEditor) { UpdateSettings(); }
24: Matrix4x4 matrixBackup = GUI.matrix;
25: GUIUtility.RotateAroundPivot(angle, pivot);
26: GUI.DrawTexture(rect, texture);
27: GUI.matrix = matrixBackup;
28: }
29: }
3) Create a new empty GameObject. Name it “mph needle”. Add the RotatableGuiItem script to it.
4) Assign your speedo needle “Texture” variable. You probably want to use a texture with a transparent alpha background for this, and bear in mind that it will rotate around the centre of the image. Adjust the “size” values to match the size of your texture.
5) Adjust the position of the texture using the X and Y position values of the GameObject in the inspector, so that it is your desired position. (probably in the centre of a normal static GUI Texture showing the mph dial face).
6) In your car script, create a var which will store a reference to this rotatable GUI item:
1: var mphNeedle : RotatableGuiItem;
7) Select your car, and drag a reference from the “mph needle” GameObject in the hierarchy into this variable slot in car script, in the inspector.
8) Now, in your car script, you can add the lines in your Update() function to calculate the MPH, and update the needle’s angle:
1: var mph = rigidbody.velocity.magnitude * 2.237;
2: mphNeedle.angle = mph;
You will probably need to adjust how far the needle turns in relation to the mph, and at what angle it starts, so you may end up with a line which looks more like this:
1: mphNeedle.angle = 20 + mph * 1.4f;
Which means the needle will be rotated by 20 degrees when the mph is zero, and will rotate 1.4 degrees for every 1 mph.
(If you want to control this script from a Javascript script, you’ll have to move the C# RotatableGuiItem into a folder called PlugIns in your assets.)
Hopefully this should get you to the stage where you have a working speedometer with a rotating needle!
Please comment, I have worked hours solving this, if you comment, it will give me some support!
I saw a question on stackoverflow.com about theme management in a Silverlight application. As I stated in my answer, there’s no specific API to manage a theme like you know it in Windows. However you have the concept of ResourceDictionnary. Yesterday I posted a link to a video from Microsoft showing different applications with very different “themes”. So you have some liberties from the minimalist UI of Windows Phone 7. But how can you change the default color while still following the guidelines of Microsoft? You can modify the styles provided in the SDK. In the folder “C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Design” you will find several XAML files:
ThemeResource.xaml contains the basic Color, SolidColorBrush and TextBlock resources. You can copy/paste this file in your application and reference it in the App.xaml to override specific styles.
System.Windows.xaml has the styles for controls like Button, CheckBox, etc. Again you can use it to override the look and feel of the widgets.
Finally, there is one folder for each of the 10 “accent” colors (blue is the default) for both the light and dark themes (the operator can provide a 11th color).
And now the look and feel of your application is customized.
One important notice: even though if you can override all the controls’ styles you should keep an eye on the implicit contract imposed by the platform i.e. the “Metro” UI guidelines. For example, it’s probably a bad idea to change the appearance of the default Button because your users will look after a particular widget in the page to save, confirm, send, etc.
Please Feelo Free To contact me and please do comment, I need them for sure.
To upload any of the file in respective folder user need to have permission for writing to the folder so please follow the following steps to prevent from the error.
Set permission to virtual directory by following steps in IIS
Right Click on virtual directory which you have created for this project. Under directory Tab you will find
1)Read
2)Log Visits
3)Index this resources
Are marked as checked (enables) in addition to this make
4)Write access enabled or checked
Click on apply
Click on ok
This will set right permission to entire virtual directory, this way we can minimize error from the front end for permission / access denied.
Other way to solve permission denied issue is to go to actual folder “images” by using physical path and follow these steps:
Right click folder
Sharing Tab
Enable share this folder radio button
Click Apply
Click Ok
If u are using this code on 2000 server you should do following:
Right click respective folder
Go to security tab
Select Everyone user
Apply full control
click on ok
Please Do comment!
Click on Add
Select New Item
Select Web User Control
Specify some Name
I have given name to this file as “uploader.ascx” and kept this file un
Start by creating a C# Windows Application project in Visual Studio and on the form drag 3 labels, 2 textboxes, 2 buttons and one progressbar.
As you can see in the form above, the first two labels are just for describing the role of the first two textboxes which are named txtUrl and txtPath. They will obviously hold the URL of the file we want to download and the local path (and filename) to where we want to save it. The default values I set in the project will download a short video from Microsoft’s Channel 9 website to C:\Filename.wmv.
The two buttons – btnDownload and btnStop – are used for starting and stopping a download, while the label below them – lblProgress – is used for showing the current progress of the download in bytes and percentage. Finally, the ProgressBar located at the bottom of the form is entitled prgDownload and it display the progress of the download on a scale from 1 to 100.
Now let’s get into coding. Switch to code view, and the first thing we need to do is to add a few using statements for the namespaces we’re going to use. Add the following 3 lines below the already existing using statements:
1: using System.Net;
2: using System.IO;
3: using System.Threading;
System.Net will be used for connecting to the web server, System.IO will be used for saving the file to the hard drive, and System.Threading will be used for the thread in which we’re going to put the downloading process.
Inside the form’s class, right above the constructor, add the following lines:
1: // The thread inside which the download happens
2: private Thread thrDownload;
3: // The stream of data retrieved from the web server
4: private Stream strResponse;
5: // The stream of data that we write to the harddrive
6: private Stream strLocal;
7: // The request to the web server for file information
8: private HttpWebRequest webRequest;
9: // The response from the web server containing information about the file
10: private HttpWebResponse webResponse;
11: // The progress of the download i ain percentage
12: privatestaticint PercentProgress;
13: // The delegate which we will call from the thread to update the form
As you can see, we are creating a few objects that we’re going to use later in the code. The object that stands out the most is not really an object, but a delegate: UpdateProgressCallback – this delegate will be used to call a method you’ll see later in our code – UpdateProgress – from inside the thread. Because you see, from inside a thread we can’t update the form elements directly (the label and the progress bar), so we need to create a delegate first, that takes the same arguments as the method. In our case the arguments are two Int64 variables that hold the number of bytes we downloaded from the server by now, and the number of total bytes the file has. Int64 is needed because this number can be really big.
Now let’s review the biggest piece of the code. The one where the file actually gets downloaded. We’ll put this code in a method called Download() which we’re going to call in a thread when the download button is pressed. Here goes the method, below it there’s more explanation of the code:
1: privatevoid Download()
2: {
3: using (WebClient wcDownload = new WebClient())
4: {
5: try
6: {
7: // Create a request to the file we are downloading
37: // When the above code has ended, close the streams
38: strResponse.Close();
39: strLocal.Close();
40: }
41: }
42: }
43:
The first line inside the method mentions that inside this method we’ll be using the wcDownload object, which can be disposed after we’re finished. If any error happens within the code, we have a finally block which closes the streams to prevent keeping a connection opened uselessly and to prevent the local file from being locked by the code.
Inside the try block we first retrieve information about the file using HttpWebRequest and HttpWebResponse objects. Note that some servers don’t give information about the size of the file, case in which we can only download blindly. If the web server did not return any information regarding the size of the file, webResponse.ContentLength will return -1.
After we get the size of the file, we define the stream that retrieves the bytes from the server, and the stream that saves the file to the hard drive. Before starting to stream the bytes down the cables, we create a buffer where we store the data that is written to the hard drive file. The buffer is 2048 bytes in size, but you can change it to a different value if you prefer.
In the while loop we loop through the buffer and write the content of the buffer to the file on the local drive. We also use the Invoke method of the form to call UpdateProgressCallback (the delegate of UpdateProgress). In the array we pass two parameters that UpdateProgress accepts: how much we downloaded until now (by measuring the length of the local stream), and how big the total file is. If you don’t have any knowledge of threading in C#, you probably would have guessed that you can update the form elements (labels, progress bars, etc.) directly, but for good enough reasons you can’t.
If we were to call the Download() method directly, then we wouldn’t have to use this.Invoke to call the UpdateProgress method. Speaking of UpdateProgress, let’s see how this method looks like:
We do a simple math calculation to get the percentage (0 to 100) and we set it on the ProgressBar to reflect the progress. We also set the label with information on the progress of the download.
We’re done with the methods for this application, now we only need to create the two event handlers for the Download and Stop buttons. Double clicking btnDownload in Visual Studio 2005 will create the Click event handler for you. Use the following code:
3: // Let the user know we are connecting to the server
4: lblProgress.Text = "Download Starting";
5: // Create a new thread that calls the Download() method
6: thrDownload = new Thread(Download);
7: // Start the thread, and thus call Download()
8: thrDownload.Start();
9: }
In the code above we start a new thread, to which we pass the name of the method (without the parenthesis). Then we start the thread. The reason we need to use a thread and we can’t just call the method from inside the Click event is because in that case our application would completely hang while downloading the file. It would become unusable and unresponsive, as if it crashed.
9: // Set the progress bar back to 0 and the label
10: prgDownload.Value = 0;
11: lblProgress.Text = "Download Stopped";
12: }
To make this a real download manager, we’d have to add resume options, and a download list so that we give the user the option to download multiple files at once, or schedule them. This will be covered in a future tutorial.
Below is the entire source code of Form1.csthat you can also view in the Visual Studio 2005 project files attached to this tutorial.
1: using System;
2: using System.Collections.Generic;
3: using System.ComponentModel;
4: using System.Data;
5: using System.Drawing;
6: using System.Text;
7: using System.Windows.Forms;
8: using System.Net;
9: using System.IO;
10: using System.Threading;
11:
12: namespace DownloadManager
13: {
14: publicpartialclass Form1 : Form
15: {
16: // The thread inside which the download happens
17: private Thread thrDownload;
18: // The stream of data retrieved from the web server
19: private Stream strResponse;
20: // The stream of data that we write to the harddrive
21: private Stream strLocal;
22: // The request to the web server for file information
23: private HttpWebRequest webRequest;
24: // The response from the web server containing information about the file
25: private HttpWebResponse webResponse;
26: // The progress of the download in percentage
27: privatestaticint PercentProgress;
28: // The delegate which we will call from the thread to update the form
by Abhi·Comments Off on Tutorial ( WP7 ) : ViewStateManger / States / Behaviours in a Windows Phone 7
Alright guys i am back with a new concept in Windows Phone 7 ( WP7 ) which is ViewStateManager. It is a really important concept for understanding visual states associated with them. If you want to create different states for your custom control then we would have to use Visual State Manager.
If you have the solution from my previous post then you can continue with it or you can download the solution here.
We will a few custom states and also learn about behaviours in this post.
Now open CompanyLocations.xaml in expression blend. Drag four TextBlock controls onto the design surface, two for the headers and two for the details and then lay them out similar to the following snapshot.
Location Details
Lets add a little more fun to this. Add two more textblock rotated at 90 degree and move the location details of the screen and also increase the font size of the headings as in the image below.
Text Rotation
Now let’s go to the top left of expression blend where we have states and lets create new state group. Click on the Add State Group button and name the state group as LocationStates. Now add two new states namely CorporateState and SatalliteState. Now your state group should look something loke the screenshot below:
Now select CorporateState to start recording for that state which you can verify by seeing the red dot at the top right of the design surface. Now this will record any changes to the state as compared to the base state. Layout the CorporateState as shown in the image below:
CorporateState
Layout for the SatelliteState is shown below:
SatelliteState
Now lets switch back to the initial state and that any changes we make will affect all the states.
Now lets include behavior to bind these states to action. So now in your assets window search for GoToStateAction and drag and drop it to both the CorporateOffice and SatelliteOffice text.
GoToStateAction
Now change the name to the GoToStateAction to the appropriate statename.