Showing posts with label unity3d car game tutorial. Show all posts
Showing posts with label unity3d car game tutorial. Show all posts

Monday, 10 June 2013

Unity3d Car Game Tutorial-10 (Adding Collision Avoidance Property To AI Cars Using Raycasting)

In this post of our tutorial series we will be looking into how o introduce the Collision Avoidance property to the AI cars that we added to our game in one of the previous posts. To do this we will be using a technique called as Raycasting.

Right so, the first question that comes to our minds is, what exactly is raycasting?
When I searched for its general definition, I found this, "Ray casting is the use of ray-surface intersection tests to solve a variety of problems in computer graphics." 
If the above definition doesn't clarify your doubts on raycasting, then here is the simplest possible line that I could think of to explain what is this Raycasting.
"Raycasting, as the name says is casting of rays, from a particular host object, along the 3d space, to detect possible collisions of the host object with the surrounding objects, having a so called Collider."

So hopefully that cleared some of the doubts, if not all. I promise to clear the rest of the doubts as we move on with this post.

To detect the collisions of the AICar with the surroundings, we will be using this raycasting. So how can we implement this raycasting?
The answer to this question lies in the script that we will be seeing now (Note that we will be using c# scripting in this tutorial, for a change. The reason is not only the change, but the scripting in c# lets you understand the code better.).

Create a c# script and name it as (say) Raycasting.

Now we will establish a direction(say along the 'x axis') for this ray to be casted along, this is done using the following statement:                                                                                                   
Vector3 forward = transform.TransformDirection(Vector3.forward) ;

Next we have to decide where this ray should start from, and for this application we want the ray to start  from the object which this script will be attached to i.e. the AICar. We do this using the following statement:
if(Physics.Raycast(transform.position, transform.forward,  5)) ---(1)          

  • This statement returns true if the ray is hitting a collider, else it returns a false.                                   
  • The '5' in the statement is the distance for which the ray is casted, from the object with the script.

Now we will use the  Debug.DrawRay to let us help visualize the casted ray, infact we will use the following statement:
Debug.DrawRay(transform.position, transform.forward*5, Color.green); ---(2)                                
which is pretty much self explanatory.

You might see that the rays casted are at the ground level, if you want to raise the rays above the ground you might want to do something like this:                                                                              
Vector3 strt;                                                                                                                                        
strt = transform.position;                                                                                                               
strt.y += .7f;                                                                                                                                     
What I did was to declare a new variable of type Vector3 and change the position of the transform i.e. transform.position        
                                                                                                          
- Now (1) and (2) would become                                                                                                                 if(Physics.Raycast(strt , transform.forward,  5)) ---(3)                                                                                       Debug.DrawRay(strt, transform.forward*5, Color.green); ---(4)       

Now we have casted a ray, what is remaining is we have to check if this ray is colliding with any of the colliders in the surroundings of the object to which this script is attached. To do that we use the following statements:                                                                                              
RaycastHit  hit;                                                                                                                                                
if(Physics.Raycast(strt,transform.forward, out hit, 5)) {                                                                            
if(hit.collider.gameObject.tag == "Player"){                             
Debug.DrawRay(transform.position, transform.forward, Color.red);                                         
}                                                                                                                                                       
}                                                                                                                                                       

  • Firstly we defined a variable of type RaycastHit to help us detect the collision.                                   
  • Next we modified the statement (3) to include this variable.                                                                         
  • Further we check if the casted ray is hitting any object which is tagged with the tag "Player".                         
  • If it does hit we are just changing the color of the ray (for now) from green to red to indicate the collision detection (You could also use Debug.Log and print something to indicate this as well.)                                                    
And as  a result we would see something like this on the gameObject (AICar here)


Once this is done what we have to add is the collision avoidance logic, whatever we did till now was the collision detectance thing.
Since we are talking about cars here we already have a target where the car should head towards i.e. the waypoints, now we will make the AICar avoid the obstacle in front of it by using the following statement:
transform.Rotate(Vector3.up, 90 * 5* Time.smoothDeltaTime); ---(5)

We avoid the obstacle by rotating the AICar in the Y axis. Vector3.up is as good as Vector3(0,1,0).
smoothDeltaTime is a smoothed out Time.deltaTime (Read Only), and we have multiplied it by some factors so as to increase the rotating angle. Since the car was already moving all we needed to do was to rotate it (towards right of the AICar here) to make sure it avoids the obstacle ahead. So the block of code now looks like:
if(Physics.Raycast(strt,transform.forward, out hit, 5)) {
if(hit.collider.gameObject.tag == "Player"){
transform.Rotate(Vector3.up, 90 * 5* Time.smoothDeltaTime);
       Debug.DrawRay(transform.position, transform.forward, Color.red);
 }
}

Next we will add two more rays so as to make it a better collision avoider using the following statements:
if(Physics.Raycast(rside,(transform.forward+transform.right*-.5f)*5, out hit, 5)) {
if(hit.collider.gameObject.tag == "Player"){
 transform.Rotate(Vector3.up, 90 * 2* Time.smoothDeltaTime);
Debug.DrawRay(transform.position, (transform.forward+transform.right*-.5f)*5, Color.red);
}
}
if(Physics.Raycast(fside,(transform.forward+transform.right*.5f)*5, out hit, 5)) {
if(hit.collider.gameObject.tag == "Player"){
          transform.Rotate(Vector3.up, -90 * 2* Time.smoothDeltaTime);
         Debug.DrawRay(transform.position , (transform.forward+transform.right*.5f)*5, Color.red);
}
}

The above two blocks of code will add two more rays and add to the robustness of the collision avoidance.


There are certain things which might throw some doubts, which is the transform.forwards and the transform.rights. The image below will help us clarify this doubt:


That image is bound to remind you of those 6th grade Math classes, and yeah this will help us clarify the questions which are on our mind now. I will list the questions, just in case:

  1. Why did i use addition of transform forwards and rights?
  2. How did we get those angled rays which are neither left nor right?


Now I will try to answer the above two questions:
You might have studied that the Y axis holds for 90 degrees and the X axis for 0 degrees. Now what do we do if we want to get a 45 degrees line, we just add the Y axis and X axis and divide them by two, the same concept is applied here.
NOTE: In unity there is no transform.left and we can play with the transform.right to make it into transform.left, you might as well have guessed from the codes above, we just negate the multiplying factors to make it align towards the left. It is just like left is negative x axis i.e. negative of right.

So we will get rays something like this:


This is all about the raycasting and collision avoidance. To make it work with the AICar, just attach the following script to the AICar and you're ready to go.
raycasting.
NOTE: Remember that the obstacles tagged with Player only are avoided and not the rest. And one more important thing is that the obstacles must and should have a collider installed in them for the obstacle avoidance to work.

Don't just copy that code blindly, try to experiment with it and then you'll get to know the magic of programming.
And yeah, just like this we are done with the understanding of Raycasting.

Share if you could grasp this concept of raycasting.

Saturday, 1 June 2013

Unity3d Car Game Tutorial-9 (Creating a Split Screen Multiplayer Game)

It is Vacation time and I want to complete this tutorial series as soon as I can so that we can start with a new series, if possible.
In this post we will be learning how to make a split screen multiplayer (2 players to be precise) racing game where in one user controls a particular car using the keys 'W A S D' and the other user controls another car using 'I J K L'.
So what are we waiting for, 3.....2.......1........ RACE

Step 1: Duplicate the 'Car' transform by right clicking and selecting 'duplicate' option ('ctrl+d' can be used as well)


Step 2: Rename it to say, 'Car1'. Reposition this Car1 as in the image below


Step 3: Go to GameObject --> Create Other --> Camera and create a new camera











And then you should get something like this on your 'Hierarchy' section.















Step 4: Attach the 'CarCamera' script to this new camera as well. And set the 'target' to 'Car1'.













Step 5: Now we will create a javascript for this 'Car1' and name it as 'Car1' itself. Now copy the 'Car' script and paste it into this 'Car1' script.
To make the 2nd car controlled using the keys ' I J K L', find the code below in the 'Car1' script:

function GetInput()
{
throttle=Input.GetAxis("Vertical");
steer =Input.GetAxis("Horizontal");
if(throttle < 0.0)
brakeLights.SetFloat("_Intensity", Mathf.Abs(throttle));
else
brakeLights.SetFloat("_Intensity", 0.0);
CheckHandbrake();
}

Now Change the 'Vertical' to 'Vertical1' and 'Horizontal' to 'Horizontal1' and save the script. As a result you should have something like this:

function GetInput()
{
throttle=Input.GetAxis("Vertical1");
steer =Input.GetAxis("Horizontal1");
if(throttle < 0.0)
brakeLights.SetFloat("_Intensity", Mathf.Abs(throttle));
else
brakeLights.SetFloat("_Intensity", 0.0);
CheckHandbrake();
}

Finally to finish this step, replace the 'Car' script on 'Car1' with this newly created 'Car1' script and fill the blank variables in the inspector section, if any, as per requirements.


Step 6: You will come across this error, if you have done the steps correctly, which says:
 "Assets/Scripts/JavaScripts/Car1.js(64,7): BCE0132: The namespace '' already contains a definition for 'Wheel'."

Now go to the 'Car1' script and 'comment' the lines of code of 'class Wheel' and you should get something like this:

/*class Wheel
{
var collider : WheelCollider;
var wheelGraphic : Transform;
var tireGraphic : Transform;
var driveWheel : boolean = false;
var steerWheel : boolean = false;
var lastSkidmark : int = -1;
var lastEmitPosition : Vector3 = Vector3.zero;
var lastEmitTime : float = Time.time;
var wheelVelo : Vector3 = Vector3.zero;
var groundSpeed : Vector3 = Vector3.zero;
}*/

Than save it to see the error being vanished.


Step 7: Now we will add the keys to control the 'Car1'.
For this, go to Edit --> Project Settings --> Input and you will see the 'Input Manager' on the 'Inspector' section. Expand the 'axes' and  do the changes as in the image below (DO the changes for the 'Horizontal' and 'Vertical' after the 'window shake y'):





















Step 8: Finally we will split the screen into two halves. To do this you need to change the 'Normalized view port rect' of both the cameras.
For the 'Main Camera' apply the values as shown in the image below:













And for the 'Camera' apply the values as in the image below:













This is it. We have a split screen two player racing game. Race with your friend and have fun.

+1 it and Share it if you found this useful. And circle me, if you still have not. Also leave your comments behind.

Thursday, 30 May 2013

Unity3d Car Game Tutorial-8 (Adding AI Cars)

Due to some reason I cannot continue making videos on Unity Car Game Tutorial Series, however I will be writing posts on it instead, hope you will appreciate the posts as you did for the videos. So let's kick off then.

In this bit of the tutorial we will be adding AI Cars to our game. Follow the steps below carefully and you shall be successful in adding AI cars and make the race game more enjoyable.
(Try to use a track which is flat and does not include up's and down's, like in the unity3d demo project)

Step 1: Drag the Car transform from the 'Project' section into the 'Hierarchy' section and name it as (say)           'AICar' (Search for 'car' in the 'search' bar in 'project' section)

Step 2: Create a Javascript named AICar_Script and add the code from the link here

Step 3: Replace the 'Car' script of the 'AICar' with the AICar_Script script

Step 4: Now create WheelColliders for the rest 3 wheels as well, as we had did it earlier for the Front Wheel (Simply duplicate WHeelFL by clicking on it once and pressing 'ctrl+d' and rename them as 'WheelFR', 'WheelRL', 'WheelRR') and synchronize them with the 3 wheels (the two images below should help in clearing doubts, if any).















Step 5:  Now drag the wheels and the wheelcolliders onto the hierarchy as in the image below





Step 6: Go to GameObject and create an empty Gameobject and rename it as 'WaypointContainer'

Step 7: Go to GameObject -> Create Other -> Sphere and create a sphere, and move it onto the WaypointContainer gameobject, and place the sphere on the terrain as if it is just kissing the surface, this is our first waypoint.

Step 8: Create waypoints like this all along the way, so that your AI car follows the waypoints (more the waypoints, better the result.) The Images below might help in clearing this point (The spheres or the small dots you see in the image on the right are the waypoints)












Step 9: Now drag this WaypointContainer onto the Waypoint Container of the AICar_Script as shown in the image below





















Step 10: Set the Gear Ratio to the values shown in the image above.

This is it, if you have followed this post correctly then you should have an AICar in your race game.
You can follow the same steps to create more AICars.

Hopefully this post is clear and hope this helped you, comment if you have any issues.

Saturday, 18 May 2013

Game Creation Tutorial - Special Episode: Unity3d Car Game (Interfacing Kinect to Unity)

In this bit of the tutorial, we will learn how to interface the Kinect camera to the Unity car racing game.


Refer to the video below for more details.






The kinect folder used here can be downloaded from the link below:
Kinect  or Kinect
                                                           







This is it for the Part-8 of this tutorial series. We'll learn more in the following posts.
Comment if you have any queries.


Saturday, 4 May 2013

Unity3d Car Game Tutorial-7 (CREATING LAP AND CHECKPOINT SYSTEM)

In this bit of the tutorial, we will add Laps and Checkpoints system to our car racing game.


Refer to the videos below for more details.






The scripts used can be downloaded below:
Checkpoints
CarCheckpoint
Timer


This is it for the Part-7 of this tutorial series. We'll learn more in the following posts.
Comment if you have any queries.


Friday, 19 April 2013

Unity3d Car Game Tutorial-6 (Saving Best Time using PlayerPrefs)

In this bit of the tutorial, we will learn how to use the PlayerPrefs to save the Best Time taken to complete the race and also save the Name of the player who completed the race in the respective time and display it on the screen.

Refer to the video below for more details.






The timer script used here can be downloaded from the link below:
Timer


This is it for the Part-6 of this tutorial series. We'll learn more in the following posts.
Comment if you have any queries.

Wednesday, 17 April 2013

Unity3d Car Game Tutorial-5 (Speed Indicator)

In this bit of the tutorial, we will learn how to add a SPEED INDICATOR to the game screen.

Refer to the video below for more details.







This is it for the Part-5 of this tutorial. We'll learn more in the following posts.
Comment if you have any queries.

Thursday, 11 April 2013

Unity3d Car Game Tutorial-4 (Stop the car after it reaches finish line)

In this bit of the tutorial, I will show you how to stop the car once it has crossed the Finish Line.


Refer to the video below for more details.

Car Game Creation Tutorial using Unity3d-4... by gluedbrain





This is it for the Part-4 of this tutorial. We'll learn more in the following posts.
Comment if you have any queries.



Unity3d Car Game Tutorial-3 (Finish Line)

In this bit of the tutorial, I will show you how to make a Finish Line to our race and stop the timer once the car has reached the finish line.

Refer to the video below for more details.

Car Game Creation Tutorial using Unity3d-3... by gluedbrain





You can find the code used in the above video below.
Timer


This is it for the Part-3 of this tutorial. We'll learn more in the following posts.
Comment if you have any queries.

Unity3d Car Game Tutorial-2 (Timer)

In this bit of the tutorial, I will show you how to setup a Timer to keep track of the time past.

Refer to the video below for more details.


Car Game Creation Tutorial using Unity3d-2 TIMER by gluedbrain


You can find the code used in the above video below.
Timer
Countdown


This is it for the Part-2 of this tutorial. We'll learn more in the following posts.
Comment if you have any queries.


Unity3d Car Game Tutorial-1 (Countdown)


Hello unity users, I'm starting a new car game tutorial for you all. I'll use the car game demo from the asset store as our reference instead of building it from the scratch.

So lets get it started then.

In this bit of the tutorial, I will show you how to set a countdown, so as to give a racing game feel.

Refer to the video below for more details:

Car Game Creation Tutorial using Unity3d-1... by gluedbrain



You can find the code used in the above video below:
countdown
This is it for the Part-1 of the tutorial series. We'll learn more in the following posts.
Comment if you have any queries.