您的位置:首页 > 移动开发 > Unity3D

unity3d中使用DoTween来控制2D摄像机视口的移动

2016-12-13 00:09 555 查看
using UnityEngine;
using System.Collections;

public class CameraMove : MonoBehaviour {

public Camera mMapCamera;

private float mMapWidth;
private float mMapHeight;

public Transform mMapRoot;

// Use this for initialization
void Start () {
mMapHeight = mMapCamera.pixelHeight;
mMapWidth = mMapCamera.pixelWidth;
}

// Update is called once per frame
void Update () {

}

public void MoveCameraToPosition(Vector3 pos, float time = 2.0f, Callback callback = null)
{
if (mMapCamera != null)
{
pos = Vector3.right * pos.x + Vector3.up * pos.y + Vector3.forward * mMapCamera.transform.localPosition.z;
{
float cameraSize = mMapCamera.orthographicSize;
float rightX = Screen.width * cameraSize / Screen.height;
float rightY = cameraSize;

Vector3 cameraPos = pos;
Vector2 maxWorldPos = new Vector2(rightX, rightY);
Vector2 maxLocalPos = mMapRoot.InverseTransformPoint(maxWorldPos);

float minX = maxLocalPos.x;
float minY = maxLocalPos.y;
float maxX = mMapWidth - maxLocalPos.x;
float maxY = mMapHeight - maxLocalPos.y;

float x = Mathf.Clamp(cameraPos.x, minX, maxX);
float y = Mathf.Clamp(cameraPos.y, minY, maxY);
float pox = x;
float poy = y;
if (x >= maxX)
{
pox = maxX;
}
else if (x <= minX)
{
pox = minX;
}
if (y >= maxY)
{
poy = maxY;
}
else if (y <= minY)
{
poy = minY;
}
pos = Vector3.right * pox + Vector3.up * poy + Vector3.forward * pos.z;
}
var tweem = mMapCamera.transform.DOLocalMove(pos, time);
tweem.OnComplete(() =>
{
if (callback != null)
{
callback();
}
});
VerifyPosition();
}
}

bool VerifyPosition()
{
float cameraSize = mMapCamera.orthographicSize;
float rightX = Screen.width * cameraSize / Screen.height;
float rightY = cameraSize;

Vector3 cameraPos = mMapCamera.transform.localPosition;
Vector2 maxWorldPos = new Vector2(rightX, rightY);
Vector2 maxLocalPos = mMapRoot.InverseTransformPoint(maxWorldPos);

float minX = maxLocalPos.x;
float minY = maxLocalPos.y;
float maxX = mMapWidth - maxLocalPos.x;
float maxY = mMapHeight - maxLocalPos.y;

float x = Mathf.Clamp(cameraPos.x, minX, maxX);
float y = Mathf.Clamp(cameraPos.y, minY, maxY);
mMapCamera.transform.localPosition = new Vector3(x, y, cameraPos.z);

return x >= maxX || x <= minX || y >= maxY || y <= minY;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: