- Home /
Question by
Tubestorm · Nov 27, 2020 at 02:03 PM ·
unity 5camera-movementscrollviewzoompinch
restrict camera movement, Camera moves out of bounds!
I'm creating a simple camera pan and scroll for my mobile game and need some help. Right now with the code I have a player can scroll of the map I created.
Do you know how I could fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScrollAndPinch : MonoBehaviour
{
#if UNITY_IOS || UNITY_ANDROID
public Camera Camera;
public bool Rotate;
protected Plane Plane;
public Transform Map;
float distance;
private void Awake()
{
if (Camera == null)
Camera = Camera.main;
Input.multiTouchEnabled = true;
}
private void Update()
{
//Update Plane
if (Input.touchCount >= 1)
Plane.SetNormalAndPosition(transform.up, transform.position);
var Delta1 = Vector3.zero;
var Delta2 = Vector3.zero;
//Scroll
if (Input.touchCount >= 1)
{
Delta1 = PlanePositionDelta(Input.GetTouch(0));
if (Input.GetTouch(0).phase == TouchPhase.Moved)
Camera.transform.Translate(Delta1, Space.World);
}
}
protected Vector3 PlanePositionDelta(Touch touch)
{
//not moved
if (touch.phase != TouchPhase.Moved)
return Vector3.zero;
//delta
var rayBefore = Camera.ScreenPointToRay(touch.position - touch.deltaPosition);
var rayNow = Camera.ScreenPointToRay(touch.position);
if (Plane.Raycast(rayBefore, out var enterBefore) && Plane.Raycast(rayNow, out var enterNow))
return rayBefore.GetPoint(enterBefore) - rayNow.GetPoint(enterNow);
//not on plane
return Vector3.zero;
}
protected Vector3 PlanePosition(Vector2 screenPos)
{
//position
var rayNow = Camera.ScreenPointToRay(screenPos);
if (Plane.Raycast(rayNow, out var enterNow))
return rayNow.GetPoint(enterNow);
return Vector3.zero;
}
#endif
}
Comment
Answer by pikachu9410 · Nov 27, 2020 at 06:16 PM
Player_//is Player GameObject
0f and 200f//is Pan range
in void Update() {}
MainCamera.transform.position = new Vector3(Player_.transform.position.x, MainCamera.transform.position.y, MainCamera.transform.position.z);
MainCamera.transform.position = new Vector3(Mathf.Clamp(MainCamera.transform.position.x, 0f, 200f), MainCamera.transform.position.y, MainCamera.transform.position.z);
$$anonymous$$athf.Clamp() is probably the better solution. In fact, it does exactly what I did anyway, except you can use it in a rectangular boundary, for example. Thanks pikachu, very cool.
Answer by Llama_w_2Ls · Nov 27, 2020 at 05:51 PM
You could find the radius from the center to a circular boundary, then put the entire camera-pan code in an if-statement which says:
if (radius > BoundaryLimit) // if distance from center is greater than boundary limit
radius = BoundaryLimit;
else
{
// Camera-pan...
}