Search Unity

Help - How to limit my camera movement ?

Discussion in 'Scripting' started by quantum_rez, Nov 28, 2012.

  1. quantum_rez

    quantum_rez

    Joined:
    Oct 23, 2012
    Posts:
    35
    Hi guys, i needing your help.

    I have code for moving my camera with my touch, but i have some trouble now, how can i limit my camera movement within my terrain?

    Thanks :D

    this is my code :
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MovingCamera: MonoBehaviour {
    5. Vector3 hit_position = Vector3.zero;
    6. Vector3 current_position = Vector3.zero;
    7. Vector3 camera_position = Vector3.zero;
    8. float z = 0.0f;
    9.  
    10. // Use this for initialization
    11. void Start () {
    12.  
    13. }
    14.  
    15. void Update(){
    16.    
    17.     if(Input.GetMouseButtonDown(0)){
    18.         hit_position = Input.mousePosition;
    19.         camera_position = transform.position;
    20.     }
    21.     if(Input.GetMouseButton(0)){
    22.         current_position = Input.mousePosition;
    23.         LeftMouseDrag();
    24.     }
    25.    
    26. }
    27.  
    28. void LeftMouseDrag(){
    29.     // From the Unity3D docs: "The z position is in world units from the camera."  In my case I'm using the y-axis as height
    30.     // with my camera facing back down the y-axis.  You can ignore this when the camera is orthograhic.
    31.     current_position.z = hit_position.z = camera_position.y;
    32.  
    33.     // Get direction of movement.  (Note: Don't normalize, the magnitude of change is going to be Vector3.Distance(current_position-hit_position)
    34.     // anyways.  
    35.     Vector3 direction = Camera.main.ScreenToWorldPoint(current_position) - Camera.main.ScreenToWorldPoint(hit_position);
    36.  
    37.     // Invert direction to that terrain appears to move with the mouse.
    38.     direction = direction * -0.4f;
    39.  
    40.     Vector3 position = camera_position + direction;
    41.  
    42.     transform.position = position;
    43. }
    44. }