Saturday, September 26, 2015

how to place 3d model into canvas image unity

Place a 3D Character into UI Canvas :- 

Process of Create a canvas panel buttons - import and adjust a camera 'Aline with view' 


  1. import 3d model into a unity project.
  2. Drag into a hierarchy 
  3. Place a camera at a side ( i mean where you want to place your character) 
  4. Create a Canvas with  Panel (Create => UI => Canvas => Panel ) and expand to entire game scene then create buttons  and place another side of your Scene.


Now your unable to view your model. because the canvas occupies entire game screen
if you want to view your character you should change the canvas settings at inspector (like fig below)

In Canvas settings => Go to render mode change Screen Space - Overlay to Screen Space - Camera and choose your main camera .... Play your game

Canvas Inspector :- 



Output Game View :-


Here is your output window... now your able to see your menu or result buttons as well as animated 3d character.


Happy Scripting...

Any Queries fell free to post a comment.... 

Tuesday, September 22, 2015

Instantiate Prefab apply AddForce unity 2d c#

About Components (How to):-



  1. Create a new project with 2D mode as shown below image.
  2. First Create Empty Game Object and rename it 'ArrowImage' at Hierarchy.
  3. Add Component 'Sprite Renderer' at Inspector
  4. Import arrow image from your Window/Mac Desktop at project folder and drop it to sprite field.
  5. Add Component 'Rigidbody 2D' at inspector of your arrow.
  6. Save Scene and drop 'Arrow Object' to Project folderNow it's convert into a prefab.
  7. Delete your 'ArrowImage' at Hierarchy
  8. Create Spawn point (where you want to release your arrow.. Probably from bow ) 
  9. Add Component 'bolow script (InstantiateScript)' to spawnPoint.
  10. Browse ArrowImage Prefab for InstantiateScript.
  11. Play your scene... Click on you Game View.

About Script Tips:-


1. You should use LateUpdate(){} for physics iterations.


Script : -



using UnityEngine;
using System.Collections;

public class InstantiateScript : MonoBehaviour {

    public Rigidbody2D arrow1;
    public int Force = 9000;

    void LateUpdate () {
        if (Input.GetButtonDown("Fire1")) {
            
            Rigidbody2D arrowRig2D;
            arrowRig2D = Instantiate(arrow1transform.positiontransform.rotationas Rigidbody2D;
            arrowRig2D.AddForce(-transform.right * Force * Time.deltaTime);
        }

    }
}



if you want to decrease image size at unity... you should increase Pixel Per Unit image import Settings as shown below image



Monday, September 21, 2015

zoom-in/out using two fingers mobile unity3d c sharp


About Testing :-

 * Attach below code to camera
 * connect your mobile through cable
 * make sure you should select unity remote device : Any Android Device at Editor setting
 * and Press Play 'Use your fingers to zoom in/out your screen'

About Coding :- 

 * You should store finger touches..
 * Store finger previous positions to Vector2
 * Find the magnitude... i mean current and previous delta positions
 * If the Camera projection is orthographic you should edit orthographicSize with some zoom constent 
 * If the Camera projection is Perspective you should edit fieldOfView with some zoom constent like script below
 * Happy Scripting


Code :-

using UnityEngine;
using System.Collections;


public class testZoom : MonoBehaviour
{
    public float perspectiveZoomSpeed = 0.5f;        
    public float orthoZoomSpeed = 0.5f;   
    
    
    void Update()
    {

        if (Input.touchCount == 2)
        {

            Touch touchZero = Input.GetTouch(0);
            Touch touchOne = Input.GetTouch(1);
            

            Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
            Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
            

            float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
            float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
            

            float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
            

            if (GetComponent<Camera>().orthographic)
            {
                GetComponent<Camera>().orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;
                GetComponent<Camera>().orthographicSize = Mathf.Max(GetComponent<Camera>().orthographicSize0.1f);
            }
            else
            {
                GetComponent<Camera>().fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;
                GetComponent<Camera>().fieldOfView = Mathf.Clamp(GetComponent<Camera>().fieldOfView0.1f179.9f);
            }
        }
    }
}




Tuesday, September 15, 2015

click to move 3d object using lerp unity c#

using UnityEngine;
using System.Collections;

public class ClickToMove2 : MonoBehaviour {
    //flag to check if the user has tapped / clicked
    //Set to true on clickReset to false on reaching destination
    private bool flag = false;
    //destination point
    private Vector3 endPoint;
    //alter this to change the speed of the movement of player / gameobject
    public float duration = 50.0f;
    //vertical position of the gameobject
    private float yAxis;

    public GameObject moveObject// GameObject if you want to move
    void Start(){
        //save the y axis value of gameobject
        yAxis = moveObject.transform.position.y;
    }
    
    // Update is called once per frame
    void Update () {
        
        //check if the screen is touched / clicked   
        if((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0)))
        {
            //declare a variable of RaycastHit struct
            RaycastHit hit;
            //Create a Ray on the tapped / clicked position
            Ray ray;
            //for unity editor
            #if UNITY_EDITOR
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //for touch device
            #elif (UNITY_ANDROID || UNITY_IPHONE || UNITY_WP8)
            ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
            #endif
            
            //Check if the ray hits any collider
            if(Physics.Raycast(ray,out hit))
            {
                //set a flag to indicate to move the gameobject
                flag = true;
                //save the click / tap position
                endPoint = hit.point;
                //as we do not want to change the y axis value based on touch positionreset it to original y axis value
                endPoint.y = yAxis;
                Debug.Log(endPoint);
            }
            
        }
        //check if the flag for movement is true and the current gameobject position is not same as the clicked / tapped position
        if(flag && !Mathf.Approximately(moveObject.transform.position.magnitudeendPoint.magnitude)){ //&& !(V3Equal(transform.positionendPoint))){
            //move the gameobject to the desired position
            moveObject.transform.position = Vector3.Lerp(moveObject.transform.positionendPoint1/(duration*(Vector3.Distance(gameObject.transform.positionendPoint))));
        }
        //set the movement indicator flag to false if the endPoint and current gameobject position are equal
        else if(flag && Mathf.Approximately(moveObject.transform.position.magnitudeendPoint.magnitude)) {
            flag = false;
            Debug.Log("I am here. Click on some other point");
        }
        
    }
}




move a object with keyboard up,down,left,right unity c#

using UnityEngine;
using System.Collections;

public class move : MonoBehaviour {

    private float speed = 2.0f;
    void Update () {
        
        if (Input.GetKey(KeyCode.RightArrow)){
            transform.position += Vector3.right * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.LeftArrow)){
            transform.position += Vector3.left * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.UpArrow)){
            transform.position += Vector3.forward * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.DownArrow)){
            transform.position += Vector3.back * speed * Time.deltaTime;
        }
    }
}



rotate a object with mouse unity3d c#

using UnityEngine;
using System.Collections;

public class rotate : MonoBehaviour {

    public float minX = -360.0f;
    public float maxX = 360.0f;
    
    public float minY = -45.0f;
    public float maxY = 45.0f;
    
    public float sensX = 100.0f;
    public float sensY = 100.0f;
    
    float rotationY = 0.0f;
    float rotationX = 0.0f;
    
    void Update () {
        
        if (Input.GetMouseButton (0)) {
            rotationX += Input.GetAxis ("Mouse X") * sensX * Time.deltaTime;
            rotationY += Input.GetAxis ("Mouse Y") * sensY * Time.deltaTime;
            rotationY = Mathf.Clamp (rotationYminYmaxY);
            transform.localEulerAngles = new Vector3 (-rotationYrotationX0);
        }
    }
}