- Home /
Move the camera only until a certain position
Can you see the blue area in this gif? I want block the camera when the player go more to left, to not see the blue area. This is the code that I'm using to move the camera:
using UnityEngine;
using System.Collections;
public class configuracoesDaCamera : MonoBehaviour {
Vector3 hit_position = Vector3.zero;
Vector3 current_position = Vector3.zero;
Vector3 camera_position = Vector3.zero;
float z = 0.0f;
public static bool bDedoNoHud;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
hit_position = Input.mousePosition;
camera_position = transform.position;
}
if (Input.GetMouseButton(0))
{
current_position = Input.mousePosition;
LeftMouseDrag();
}
Debug.Log("bDedoNoHud" + bDedoNoHud);
}
void LeftMouseDrag()
{
if (!bDedoNoHud)
{
// 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
// with my camera facing back down the y-axis. You can ignore this when the camera is orthograhic.
current_position.z = hit_position.z = camera_position.y;
// Get direction of movement. (Note: Don't normalize, the magnitude of change is going to be Vector3.Distance(current_position-hit_position)
// anyways.
Vector3 direction = Camera.main.ScreenToWorldPoint(current_position) - Camera.main.ScreenToWorldPoint(hit_position);
// Invert direction to that terrain appears to move with the mouse.
direction = direction * -1;
Vector3 position = camera_position + direction;
transform.position = position;
}
}
}
Answer by salex100m · Jan 02, 2017 at 03:42 AM
assuming your map is 500x500..... just set the camera Max and min positions if it goes past wherever is too far for your taste.
if( camera.position.x > 475 ) camera.position.x = 475;
if(camera.position.y >475) camera.position.y = 475;
it's not that easy, but thats the idea. (Hint, you can't change transform.pos.x/y/z directly.) so say camera.position = new Vector3( max_X, curr_Y, curr_Z) for example....
Answer by Ninjapro2k_ · Jan 02, 2017 at 04:12 AM
@salex100m has a great answer. You may also want to look into Mathf.Clamp
Your answer
![](https://koobas.hobune.stream/wayback/20220612103845im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Camera follow Player Script - Problem 1 Answer
Panorama reset position/angle. 0 Answers
Switching to the player camera 1 Answer
Camera.ViewportToWorldPoint giving different values 0 Answers