Pages

Showing posts with label Unity 3d. Show all posts
Showing posts with label Unity 3d. Show all posts

Tuesday, October 28, 2014

How To touch To orbit around player for Android in unity

Hi! readers I've recently converted the Mouse orbit Script that comes in standard assets to work with android and iOS touch devices. It's something very basic (easy to understand and modify) and very short. Just drag this script to the camera and assign a target around which you want the camera to rotate. Here it is...

//The standard mouse orbt script converted to work with touch devices (android and iOS) by Newtonians. Feel free to use or modify
//Check out the blog http://newtonians3d.blogspot.com/
using UnityEngine;
using System.Collections;

public class touchorbit : MonoBehaviour {
    private float x;
    private float y;
    public float xspeed;
    public float yspeed;
    private Touch touch;
    public float distance = 10;
    public Transform target;
    Rect margin;
    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
        margin = new Rect(Screen.width * 0.5f, 0, Screen.width, Screen.height * 1.0f);
        float count = Input.touchCount;
        for (int i = 0; i < count; i++)
        {
            Touch tc = Input.GetTouch(i);
            if(margin.Contains(tc.position)){
            x += tc.deltaPosition.x * xspeed * 0.02f;
            y -= tc.deltaPosition.y * yspeed * 0.02f;
            }
        }
        Quaternion rotation = Quaternion.Euler (y, x, 0);
        Vector3 position = rotation * (new Vector3(0.0f, 0.0f, -distance)) + target.position;
       
        transform.rotation = rotation;
        transform.position = position;
    }
}


Another thing is that I've converted the original js script to c# so that it would be easier for a user to integrate the script into his projects.

This script is tested and works well but if you have some problem, please tell me.
Thanks.

Saturday, September 6, 2014

Simple Third Person Character Movement in Unity 3d (with Mecanim) - I

Hi, welcome back readers. Many a people want to make a third person game in unity. Here is simple third person movement tutorial with my project folder too. In next tutorials, we'll add jumping, sprinting and some other basic moves.Have a look at this video of the completed tutorial in action.





This is what we will make after the tutorial.

Be patient because it may seem to be a long tutorial but it is as informative as long it is. Also it is so user friendly and easy to understand that a person not knowing anything about Unity may also give it a try.

To make a third person game you will need a 3d character model and some basic animations like walk, idle etc. You can use your own models but if you don't have it I will provide you the sample assets which are used in this tutorial here -

http://www.4shared.com/file/0R8OkHHhce/Free_Assets.html

The model used is the free soldier model made by Mixamo and the animations are provided by unity in their raw mocap data unitypackage. And that crappy environment is made by me it's not much good cause i'm not a 3d modeller.

1. So first of all we will open unity and make a new project. So go to File --> create new project to make a new project and under 'import the following packages' select scripts.unitypackage as need the camera orbit script contained in it And name the project of your choice. you will see something like this.-


Now we will import the Free assets package (link are provided above) by going Assets --> import package --> custom package and then import the file which you downloaded. Select all items and click import.
Now you will see a soldier model, idle and walk animations and the crappy environment i was talking about. (notice that it looks like a simple box in project view but it's actually a interior model)

2. So now we will prepare our scene for our use. So drag the 'dfdf' model (the crappy environment) into the scene area and you will see the model int the scene view (now you will see the interior part)


As the environment looks very dull now we will add a light to illuminate it. So add a point light and place it in the center of room just below the ceiling to get a decent lighting


You can play with the range, colour and intensity of lights to get the lighting as you want. Now drag the soldier also and place it at any place in the interior. Now save your scene.

3. As our scene preperation is done now we will make the animating part done. Go to the animation folder in project view and you will see an idle and walk animation. The mecanim system uses animator controller for the logical creation of animation states So, create a new animator controller by right click --> create --> Animator controller and name it and double click it to open the animator window like this -


If you don't know the very basics of animator controller please take a look at unity Docs they have  lot of information about it. Basically, in mecanim you create states (animation clips) for different animation like walking, standing, running and then you connect them with transition with some conditions. And if that condition is met the transition will occour from one state to another othewise it will loop in the present state.

So click on the tiny arrow in the idle animation icon and it will show you the content and you will see a 'playing' icon with name 'idleR...' (it's actually the animation part of the Fbx file) and Drag it into the animator window and it will create a new state with it. like this -



Now also drag the walk animation in animator. You will notice that the idle animation is of yellow colour because it's the default state that will be played after starting game. You can change the default state by right clicking on state --> 'Set as default'. Now click the + icon just ahead the parameters to add a new parameter and set its type as float and then name it speed. Now we will create transitions from idle to walk.
For that right click idle state and click on make transition and then click on the walk state like this.


Now click on transition and you will see its properties in inspector. There you will see a property called condition. when the conditions specifies under this field met, the transition will  occour. By default a transition occours when the animation completes one loop ie. exit time. But we need it to be changed by speed parameter so change the exit time to speed. Now there is a field for a greater than or less than value which specify the condition for the transition, We need the walk animation at value of speed 1 and the idle at 0 so change its value to greater than 0.5.
Similarly make a transition from walk to idle, now with parameter speed less than 0.5

Now go back to the scene and select player gameobject, In the inspector under the Animator there will be a property called controller So, drag the animator controller we just made into that field and our animation part is done.

4.LOGIC Behind our third person shooter. Like in most of the third person games present today like max payne, gta 4. The player rotation system is relative to camera and user inputs eg. when user press right arrow, first the player rotates in the exactly right direction as viewed by user (or you can say camera) in other words the player rotates in the direction of camera + 90 degrees and start walking in that direction  similarly if he presses down arrow the new rotation will be camera +180 degrees and if player presses both right and up arrow the direction will be camera + 45 degrees. Here is a diagram of all possible values of The new Rotations.

 

5. Now we will do the scripting part so make a new C# script and name it playerscript or whatever you like And then open the script in editor.


It will show some template for you to start with. We will first declare some variables which are essential for our need. So write this above all methods but inside the class just below the line that declare your class playerscript : Monobehavior like this -

public class playerscript : MonoBehaviour{
Animator anim;
public Quaternion newrotation;
public float smooth = 0.05f;
public Transform camera;

anim is the animator that will take care of assigning the speed parameter we created in animator window through user inputs. Next we declare a quaternion, As this tutorial is for beginners i will not talk much about them because they are not easy to understand i also not use them very much because of that. As in general we all know that quaternions store rotations and the newrotation variable will store the current rotation the input keys shows. Later we will slerp the player rotation from its rotation to this newrotation which I was telling about when explaining the logic of third person shooter.
The third variable smooth specify how smoothly player rotates in the intended direction. And the last variable specify the Transform of camera, As you know all the rotations will be relative to this cameras rotation, so this is also very important for us.

Now under the void start write this -

anim = GetComponent<Animator>(); 

This will access the animator from the player through scripting.
Then we will take the user input through Axis So, write this under void Fixed Update

 float v = Input.GetAxis ("Vertical");
 float h = Input.GetAxis ("Horizontal");
 movement(v,h);

These will store user horizontal and vertical inputs in variables To be used  later. And the next line will get error at this  time because we havn't made any fucntion. Next we will create that function we called earlier that will move our player according to inputs. The basic syntax for a function in C#  is return type function-name(arguments){main body} so above all methods but inside the class create a new function for movement which take Input Axis as arguments like this -

  void movement (float v, float h) {
        }


Now under this function write this -

    if (h != 0f || v != 0f) {
    //checking if the user pressed any keys
            rotate(v,h);

    //rotates the player in the intended direction
            anim.SetFloat ("speed",1);

    //then move the player in that direction
        }
        else {
            anim.SetFloat ("speed",0);

    //Stop the player if user is not pressing any key
        }


Here we again called another function rotate we do not created which we will do next. First of all it checks if their is an input from user and then sets the speed of animator to 1 (remember we aplied the condition from idle to walk with greater than 0.5, thus the condition is met and player will start moving).
Now comes the main thing of rotating the player in relative to camera. We have already invoked the rotate function so now we will create that function.

  void rotate(float v,float h) {
     }

Add this whole code under this function

    if (v > 0)
        {
            if (h > 0)
            {
                newrotation = Quaternion.Euler(0,camera.eulerAngles.y+45,0);
            }
            else if (h < 0)
            {
            newrotation = Quaternion.Euler(0,camera.eulerAngles.y+305,0);
            }
            else
            {
            newrotation = Quaternion.Euler(0,camera.eulerAngles.y,0);
            }
        }
        else if (v < 0)
        {
            if (h > 0)
            {
                newrotation = Quaternion.Euler(0,camera.eulerAngles.y+135,0);
            }
            else if (h < 0)
            {
                newrotation = Quaternion.Euler(0,camera.eulerAngles.y+225,0);
            }
            else {
                newrotation = Quaternion.Euler(0,camera.eulerAngles.y+180,0);
            }
        }
        else
        {
            if (h > 0)
            {
            newrotation = Quaternion.Euler(0,camera.eulerAngles.y+90,0);
            }
            else if (h < 0)
            {
            newrotation = Quaternion.Euler(0,camera.eulerAngles.y+270,0);
            }
            else {
                newrotation = transform.rotation;
            }
        }

     

Don't think this code is too big this code is also as easy understand as big it is. In short what it does sets the new rotation's value according to user's input and relative to camera. Remember the diagram -


Now so that the new rotation's value is specified we will slerp it into player rotation so add this code below code above;

newrotation.x = 0;
newrotation.z = 0;
//We only want player to rotate in y axis
 transform.rotation = Quaternion.Slerp (transform.rotation,newrotation, smooth);

//Slerp from player's current rotation to the new intended rotaion smoothly 

Now, with that our scripting part is done and our tutorial is almost finished.

 6. Go back to the Unity Editor and assign this script on the the player. And in the inspector assign the camera Transform field with the main camera. Now assign the Mouse orbit script to our main camera and assign the target to our player and set the distance to 1.3. 

Then hit play and you will observe a realistic third person character movement. Your character is moving as it should but there is one problem that rotates around the legs of character because pivot point of character is at legs.
To solve that problem just click on gameObject --> create empty and a new game object is created, now rename it as target and place it just at the chest of our soldier (Place it in character carefully and check it from all views so that it is at correct position.) now make this object a child of player by simply dragging the object onto the player's gameobject in hierarchy. Now in the target field of Orbit script of main camera drag this newly created target object and then hit play and enjoy your created Third person game.

To add the physics to the player and increase the realism simplay add a capsule collider and rigidbody to player see it in action You can also bake the environment with unity's lightmapper to add more realism. 

Here is the link to our project folder 

http://www.4shared.com/rar/ziw5DVrSce/Simple_TPS_Character_movement.html 
 
Thank you for reading my this very long tutorial, feel free to give any suggestions or complaints. Keep checking for further updates to this tutorial in which we would be trying to add jumping, sprinting and some cool basic moves. One more time thank you and have a good day.

Saturday, July 12, 2014

Tips #1 Rotating player with camera in TPS

I will show how we can rotate player with the camera, just like in max payne 2.

what we have to do is create and apply a script on player.
In function update, write

transform.eulerAngles.y=Camera.main.transform.eulerAngles.y

transform.eulerAngles.y will give the state of rotation of main camera about vertical axis whose value we are assigning to the state of rotation of the player. We can use other cameras as well, for that instead of camera.main.transform, we have to give another variable of type transform whose rotation we want the player to follow. Keep reading for more tips.

Wednesday, July 2, 2014

One Way Platform : Unity Tutorial

Hi friends! Here is the tutorial for making One Way platforms in unity. I've got a very simple technique to do this job so that no one gets stuck at this problem.

Here is what you have to do.

Make a platform and add a box collider to it.

Create a Gameobject (it is used for collision checking), as a child to the platform,name it as colcheck, and add a box collider to it just below the box collider of the platform. Make sure that "is trigger" checkbox is on so that we can check if the character or any kind of player is in contact with it or not. It should look something like this.






Go to tags and layer an create a new tag 'platform' and assign this to all the colcheck game objects.
Now we will write a script and add it to the colcheck game object we just created. Here it goes.

function Start () {

var colliderofplatform : BoxCollider2D;

//It is collider of main platform, assign it in inspector
 
var oneway : boolean;

//this variable will be made true when the players is just below the platform so that the Box collider of collision checking game object can be disabled that will allow the player to pass through the platform

}

function Update () {

if (oneway)
  colliderofplatform.enabled=false;


 if (!oneway)
  colliderofplatform.enabled=true; 


//Enabling or Disabling the platform's Box collider to allowing player to pass  
}



function OnTriggerStay2D(coll : Collider2D) {

if (coll.gameObject.tag == "platform")
   oneway = true;

 //Checking the collison of the collision checking gameobject we created for checking if the player is just below the platform and needs to ignore the collison with the platform}
 
}

function OnTriggerExit2D(coll: Collider2D) {
   oneway = false;


//It is done so that we can reactivate the collider of the platform for the player to stand on that platform
}


Now you will see that our one way collider is working the way it should. If there is some problem with it, add it to comments and I will fix it.

I'll upload the project file also. Keep reading, keep enjoying and playing with Unity, thats a nice engine. 

Sunday, June 29, 2014

A Simple and Efficient Touch And Drag RigidBodies For Unity 3D (Beginner Friendly) - Part 2

Welcome To Part 2 of Making a touch to drag script in unity. In this part we will add more realism to our project to make it more enjoyable.
1. After the completed first part you'll notice that when we released touch input the rigidbody do not fall realistic. It falls like its animated and not by physics. There is a very there is a very simple trick to do that. We will simply add a force to that object when the TouchPhase is ended (user released touch) equal to its delta position (The position delta since last change). To do that-
First declare a variable above all method and under class like we did in part 1 

private Vector2 deltaposition; 
privat float speed = 100;

We need to use a variable to store delta position because When the TouchPhase.Ended is called the delta position becomes zero and we can't use it in case Ended. The deltaposition is a very small value so we will multiply it by speed. Now add this under TouchPhase.Moved 

deltaposition = touch.deltaPosition;

It stores the Value of current touch delta position. And when the finger's released it do not get changed to zero, instead it remains the Last delta position untill touch's released. And add this line in TouchPhase.Ended

selection.rigidbody.AddForce(deltaposition.x*speed,deltaposition.y*speed,0);

Now you will notice the difference that how natural it looks now than before. But there is one problem left when you drag an object too fast the object will sprung into sky and never comes back ie we need to limit the deltaposition value not to exceed a specific value, for this we will use Mathf.Clamp so add this line under void update but remember to put it outside the for each loop - 
 
Mathf.Clamp (deltaposition.x, 0, 1);
Mathf.Clamp (deltaposition.y, 0, 1);


This will Limit the deltaposition value perfectly. If your not satisfied you can change the values of clamp according to your need.
Now this problem can be said solved.

Check Point - The script After All of above steps (check if have the same one)
Since, we are dragging any object on XY plane we do not add any force on z axis. But is want more functionality like moving in XZ plane you can easily do this by just simply rotating your plane 90 degrees so it faces the ground.
For now I have these improvement for our script, I will edit this post whenever i will come up with some new improvement to this project.

Thanks for reading my blog, bye;

Friday, June 27, 2014

A Simple and Efficient Touch And Drag RigidBodies For Unity 3D (Beginner Friendly) - Part 1

Hi! Looking for a simple and efficient Touch and Drag RigidBodies scripts for developing for Android, iOS or any other phones? Here is the tutorial for you.
First of all make a new project or you can also work in an existing project beacuse it will work for any RigidBody.

 

You will see a clear empty scene with just a Camera. We will attach our script with that camera. Here is how it looks without anything-




But for now click on create menu in hierarchy and then on plane to add a plane to your scene. This plane is very useful because we will later use it for Raycasting (with masking) to know current touch position. You will understand about it after some time. Now click on Layers and then Add layer. You will see 8 builtin layers which are not important for us add a user Layer 8 with any name, i used the name 'plane'. Make sure the plane's rotation is exactly with the camera and then parent the plane to the camera.
If you have not done something wrong your scene will look like this. (except the parenting step because i edited that later)


Now Add a Ground and some cubes or anything you want for Testing Our scripts, Just ensure that a rigidbody is attached to that cube or whatever you have choosen. disable the mesh renderer of the plane we created earlier for Raycasting. And Last add a point light to the scene to make it look 'fancy'. And
Here is our final scene setup.



Now comes the scripting Part, for that make create a new C# script and name it 'Drag' (as usual, without quotes) or whatever you like Then, open that up, And you will get something like this 

If you are a Basic user you should know that what void start and update does for your convinience.
Our First  Step is to declare the Variables we will use for our purpose (we will understand about them Later) - Add this above all of methods but under the class otherwise unity will bring an error.

 public Transform plane;
 private Transform selection = null;
 private Vector3 dist;


The plane is the plane we created earliear. Just assign this variable with the plane which we make the child of camera via inspector.
The selection transform will be assigned to the object which the user wanted to drag.i'll explain that later.
The Vector3 dist calculates the distance between the hit point and the transform of the selected object
Now add a foreach loop with array input.touches. If you don't understand, here is what i mean (add this under void update)

foreach(Touch touch in Input.touches)
        {


        }

This type of loop execute the code inside for any touches that exist in Input.Touches. If you still don't understand i refer you to unity Documentation.
Inside the foreach loop, Declare these variables - 

  Ray ray = Camera.main.ScreenPointToRay(touch.position);
 RaycastHit hit;


The first variable is a ray which goes in the direction pointed by touch input and the second is a RaycastHit which will give us info ablout the Raycast such as colliding object etc. The camera.main.ScreenPointToRay converts the user's 2d input into a 3d line going into the direction pointed by user's input position.

Now, Add a switch under the foreach loop for Touch Phases. code - 

 switch (touch.phase) {
            case TouchPhase.Began:

                break;
            case TouchPhase.Moved:

                break;
            case TouchPhase.Ended:

                break;
            }


This switch switches whether the user has began the Touch movement, or he is still touching or he has ended. Truly I don't know very much about switches but it is enough for all of us.

 Add this line to void Start of your script

plane.collider.enabled = false;
This will make the collider disabled by start. You can ignore its explanation because you will automatically understand it later.

CheckPost - If you have reached here successfully, your script will look like this -



using UnityEngine;
using System.Collections;

public class Drag : MonoBehaviour {

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
   void Update () {
        foreach(Touch touch in Input.touches)
        {
            Ray ray = Camera.main.ScreenPointToRay(touch.position);
            RaycastHit hit;
            switch (touch.phase)
            {
                case TouchPhase.Began:
               
                    break;
                case TouchPhase.Moved:
               
                    break;
                case TouchPhase.Ended:
               
                    break;
            }
        }
    }
}








If unity bring any error It means you done something wrong (Although it will give a warning about unused variables). Ok, So now the Setup is complete now w'll do some serious coding.
 Add these lines under case TouchPhase.Began: , TouchPhase.Moved:and TouchPhase.Ended: (actually replace the all code below with all the code in your script inside switch staement)


switch (touch.phase)
            {
                case TouchPhase.Began:


                if(Physics.Raycast(ray, out hit, 100))
                {

                 
                  if (hit.rigidbody !=null)
                    {
                      selection = hit.rigidbody.transform;
                      plane.transform.position = hit.point;
                    }
                }
                dist = new Vector3(hit.rigidbody.transform.position.x,hit.rigidbody.transform.position.y,hit.rigidbody.transform.position.z) -  hit.point ;
                plane.collider.enabled = true;
                    break;


                case TouchPhase.Moved:


                int layerMask = 1 << 8;
                if(Physics.Raycast(ray, out point, 100,layerMask))
                {

                   

                selection.rigidbody.constraints = RigidbodyConstraints.FreezePosition;
                selection.transform.position = point.point + dist;
                }
                    break;


                case TouchPhase.Ended:

                selection.rigidbody.constraints = RigidbodyConstraints.None;
                selection = null;
                plane.collider.enabled = false;
                    break;
            }


At First Sight, this looks like a mess of code but you will understand it. that's the reason i make the title Beginner friendly
I'll explain it step-by-step 

Under TouchPhase.Began 
We fire A raycast from the ray we created earliear which originates and move towards the direction of touch input.Then, If it hits on a rigidbody assign the selection variable to the transform of that rigidbody, and set the position of the plane for raycasting to the point where the raycast hit. Then we calculated the distance between the hit point and colliding rigidbody's transform. This offset(var dist) is very essential because if we will not use it The object center will always be at your finger's position even if you pulled it from the corner of object which will give jerky motion to object.
And at last plane collider is being enabled to detect touch position in Moved phase.

Under TouchPhase.Moved
Declaring a int for ignoring the raycast for all object except the plane (which we defined earlier in scene setup). Then raycast the current touch position which hit the plane and then assign the position of that point to the rigidbody the raycast hit(in Touchphase.began). Then we freezed the movement of Rigidbody To make it move according to the touch movement without falling with gravity.(actually this make dragging rigidbody very enjoyable as the rigidbody will only rotate in air but not fall).

Under TouchPhase.Ended
when user stopped touching the screen. We just rollback the changes we did like we disabled the freeze position constraint. And empty the selection variable. And also disabled the plane collider so that it will not come in the way when the user will again try to drag another rigidbody. (that's why we disable the collider in void start, I hope you guessed that earlier).

And hit the play button if you are using realtime debugging or build and play in your device (if you have one) or in a emulator and you will see the cube or the test rigidbody you choosed acording to your finger. At this point although it look very good but not totally realistic. We will add more realiatic effects to this in part 2. 
That is all for part 1. In Part 2 we will add some more physical effects to make it more real and enjoyable.

Here is The unitypackage of this project if you just want some instant Action or you feel comfortable to understand it better with source code. So here is the link from 4 shared - 

http://www.4shared.com/file/2DBk80hgce/Touch_n_Drag_part-1_source.html

Let me know if you have problems with download. I'll make the part as soon as i can. Thanks for reading the post. I'll hope you like it. bye 

[EDIT] The part 2 is complete you can check it out at this link - 
www.newtonians3d.blogspot.com/2014/06/a-simple-and-efficient-touch-and-drag_29.html

Thursday, June 26, 2014

Welcome to Newtonians Blog

Welcome readers, this is the Newtonians blog. We are game designers and programmers. When I was a newbie, I found it difficult to find tutorials which could help me and give an easy way to get things moving. I want to help such people who are in need of  some help. Basically, the blog is to help out the Unity 3d users. Unity 3d is very good and user friendly game engine for beginners. Its very easy to learn make your own masterpiece and show the world what you can do. We will soon start posting tutorials, tricks and tips. Stay in touch.

www.newtonians3d.blogspot.com