restrict camera movement, Camera moves out of bounds

1.5k Views Asked by At

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. I got the code from this youtube video (for context) https://gist.github.com/ditzel/836bb36d7f70e2aec2dd87ebe1ede432
https://www.youtube.com/watch?v=KkYco_7-ULA&ab_channel=DitzelGames

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
}

1

There are 1 best solutions below

3
Leoverload On

You can put in the update a control with the bounds of your area with a bool like this :

if(Camera.transform.position.x > valuexmax || Camera.transform.position.x < valuexmin
      || Camera.transform.position.y > valueymax || Camera.transform.position.y < valueymin)
   {
     InBounds = false; //just a bool variable set to true in start
   }

And then you can put in the scroll something like this

if (Input.touchCount >= 1 && InBounds == true)
    {
        Delta1 = PlanePositionDelta(Input.GetTouch(0));
        if (Input.GetTouch(0).phase == TouchPhase.Moved)
            Camera.transform.Translate(Delta1, Space.World);
    }

if(InBounds == false)
{   
      // reset position
 }