I can't drag the screen

I’ve this script. I just put it in Main Camera. However, it doesn’t work:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraMove : MonoBehaviour
{
    private Vector3 Origin;
    private Vector3 Difference;
    private Vector3 resetCamera;

    private bool drag = false;
    private void Start()
    {
        resetCamera = Camera.main.transform.position;
    }

    // Update is called once per frame
    private void LateUpdate()
    {
        if (Input.GetMouseButton(0))
        {
            Difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition)) - Camera.main.transform.position;
            if (drag == false)
            {
                drag = true;
                Origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);

            }
            else
            {
                drag = false;
            }

            if (drag)
            {
                Camera.main.transform.position = Origin - Difference;
            }

            if (Input.GetMouseButton(1))
            {
                Camera.main.transform.position = resetCamera;
            }

        }
    }
}

If you have any idea, I’d be much appreciated.

Lines 23 through 32 are setting the boolean one frame only to immediately clear it the next frame.

1 Like

I have a drag-camera and drag-world-object script that I keep here:

Beyond that, remember that camera stuff is pretty tricky… you may wish to consider using Cinemachine from the Unity Package Manager.

There’s even a dedicated forum: Unity Engine - Unity Discussions

If you insist on making your own camera controller, the simplest way to do it is to think in terms of two Vector3 points in space: where the camera is LOCATED and where the camera is LOOKING.

private Vector3 WhereMyCameraIsLocated;
private Vector3 WhatMyCameraIsLookingAt;

void LateUpdate()
{
  cam.transform.position = WhereMyCameraIsLocated;
  cam.transform.LookAt( WhatMyCameraIsLookingAt);
}

Then you just need to update the above two points based on your GameObjects, no need to fiddle with rotations.

1 Like