Home > OS >  Unity 2d: Camera resets when beginning to drag
Unity 2d: Camera resets when beginning to drag

Time:10-28

So I am trying to move the camera through dragging with the mouse and it works but everytime I begin to drag again, the camera resets to 0, 0 and I don't understand why. Here's the script:


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

public class CameraMovement : MonoBehaviour
{
    Camera cam;
    Vector2 mouseOffset;
    Vector2 dragOffset;
    Vector3 mousePosition;
    Vector3 mousePixPos;

    void Start()
    {
        cam = Camera.main;
    }

    void Update()
    {
        //From Mouse Position in Pixel to Worldposition
        mousePixPos = Input.mousePosition;
        mousePixPos.z = cam.nearClipPlane;
        mousePosition = cam.ScreenToWorldPoint(mousePixPos);
        

        if (Input.GetMouseButtonDown(2))
        {
            mouseOffset = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
        }
        if (Input.GetMouseButton(2))
        {
            dragOffset = new Vector2(mousePosition.x - mouseOffset.x, mousePosition.y - mouseOffset.y);
            transform.position = new Vector3(transform.position.x - dragOffset.x, transform.position.y - dragOffset.y, -10);
        }
    }

}

The MouseOffset is the Offset of the mouse from the camera meaning the middle of the gamescreen. The dragOffset is the Offset of the mouse from the earlier set MouseOffset. Pls help

CodePudding user response:

Try this


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

public class CameraMovement : MonoBehaviour
{
    Camera cam;
    Vector2 dragOffset;
    Vector3 mousePosition;
    Vector3 mousePixPos;
    Vector3 mouseStartPos;
    Vector3 myStartPos;

    void Start()
    {
        cam = Camera.main;
    }

    void Update()
    {
        //From Mouse Position in Pixel to Worldposition
        mousePixPos = Input.mousePosition;
        mousePixPos.z = cam.nearClipPlane;
        mousePosition = cam.ScreenToWorldPoint(mousePixPos);
        

        if (Input.GetMouseButtonDown(2))
        {
            mouseStartPos = mousePixPos;
            myStartPos = transform.position;
        }
        if (Input.GetMouseButton(2))
        {
            dragOffset = new Vector2(mousePixPos.x - mouseStartPos.x, mousePixPos.y - mouseStartPos.y);
            transform.position = new Vector3(myStartPos.x - dragOffset.x, myStartPos.y - dragOffset.y, myStartPos.z);
        }
    }

}
  • Related