Unity,脚本拖动相机

时间:2017-04-30 01:23:42

标签: c# unity3d

我在XY平面上有2D网格。我有以下脚本将相机移动到平面上,相机从(0,0,-10)开始。

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

public class DragMap : MonoBehaviour {
private float dist;
private Vector3 MouseStart;
private Vector3 derp;

void Start () {
    dist = transform.position.z;  // Distance camera is above map
}

void Update () {
    if (Input.GetMouseButtonDown (2)) {
        MouseStart = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        MouseStart = Camera.main.ScreenToWorldPoint (MouseStart);
        MouseStart.z = transform.position.z;

    } 
    else if (Input.GetMouseButton (2)) {
        var MouseMove = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        MouseMove = Camera.main.ScreenToWorldPoint (MouseMove);
        MouseMove.z = transform.position.z;
        transform.position = transform.position - (MouseMove - MouseStart);
    }
}
}

但我不能为我的生活找出要改变的内容,这样如果我将鼠标向右拖动,相机会向左移动,反之亦然。同样,如果我向上拖动鼠标,我想将相机向下移动,反之亦然。救命!

感谢您的回复。

-DrOmega。

2 个答案:

答案 0 :(得分:1)

你需要否定MouseMove向量的x才能翻转x移动:

MouseMove = new Vector3(-MouseMove.x, MouseMove.y, MouseMove.z);

答案 1 :(得分:1)

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

public class DragMap : MonoBehaviour {
private float dist;
private Vector3 MouseStart;
private Vector3 derp;

void Start () {
    dist = transform.position.z;  // Distance camera is above map
}

void Update () {
    if (Input.GetMouseButtonDown (2)) {
        MouseStart = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        MouseStart = Camera.main.ScreenToWorldPoint (MouseStart);
        MouseStart.z = transform.position.z;

    } 
    else if (Input.GetMouseButton (2)) {
        var MouseMove = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        MouseMove = Camera.main.ScreenToWorldPoint (MouseMove);
        MouseMove.z = transform.position.z;
        transform.position = transform.position - (MouseMove - MouseStart);
    }
}
}

这里有一个简单的解决方法。如果要同时翻转x和y,请将“-(MouseMove-MouseStart)”替换为“ +(MouseMove-MouseStart)”