【问题标题】:Unity - Limit Camera Movement XY axisUnity - 限制相机移动 XY 轴
【发布时间】:2014-03-18 07:46:03
【问题描述】:

我有以下代码,它非常适合使用可拖动鼠标滚动地图。我正在尝试定义限制,以便我不能在 x 或 y 坐标中滚动太远。我见过各种代码示例,例如: “transform.position.x = Mathf.Clamp(-100, 100);”尽管无法将其合并到代码中。我对这一切有点初学者,刚刚完成了一个 2D 动画僵尸教程,并且有一个可以滚动的相机,但想限制它可以在任何给定方向上滚动的距离。

谢谢大家

亚当

using UnityEngine;
using System.Collections;

public class ViewDrag : MonoBehaviour {
    Vector3 hit_position = Vector3.zero;
    Vector3 current_position = Vector3.zero;
    Vector3 camera_position = Vector3.zero;
    float z = 0.0f;

    // Use this for initialization
    void Start () {

    }

    void Update(){
        if(Input.GetMouseButtonDown(0)){
            hit_position = Input.mousePosition;
            camera_position = transform.position;

        }
        if(Input.GetMouseButton(0)){
            current_position = Input.mousePosition;
            LeftMouseDrag();        
        }
    }

    void LeftMouseDrag(){
        // From the Unity3D docs: "The z position is in world units from the camera."  In my case I'm using the y-axis as height
        // with my camera facing back down the y-axis.  You can ignore this when the camera is orthograhic.
        current_position.z = hit_position.z = camera_position.y;

        // Get direction of movement.  (Note: Don't normalize, the magnitude of change is going to be Vector3.Distance(current_position-hit_position)
        // anyways.  
        Vector3 direction = Camera.main.ScreenToWorldPoint(current_position) - Camera.main.ScreenToWorldPoint(hit_position);

        // Invert direction to that terrain appears to move with the mouse.
        direction = direction * -1;

        Vector3 position = camera_position + direction;

        transform.position = position;
    }
}

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    您遇到的具体错误是什么?我想这类似于无法修改position 的返回值,因为它不是变量。

    如果是这种情况,您应该能够一次设置整个位置向量。因此,请尝试以下方式:

    var pos = transform.position;
    transform.position = new Vector3(
        Math.clampf(pos.x, -100, 100), 
        Math.clampf(pos.y, -100, 100),
        pos.z
    );
    

    您可能需要交换夹紧 Y 和 Z,这取决于您使用它们的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2021-03-10
      • 1970-01-01
      • 2016-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多