Unity版本为5.3.2
这篇文章主要是实现一下2d游戏中相机的跟随
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/40d0f0a47e6b4d878637e092ed1a1258.png)
首先随便创建一个2d游戏场景,然后创建一个空物体,在空物体上加上一个boxcollider2d,调整大小,使它的范围包住背景(不是包住相机),也就是图中的边框
上代码:
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
public Transform player;
public Vector2 Margin;
public Vector2 smoothing;
public BoxCollider2D Bounds;
private Vector3 _min;
private Vector3 _max;
public bool IsFollowing{ get; set; }
void Start(){
_min = Bounds.bounds.min;
_max = Bounds.bounds.max;
IsFollowing = true;
}
void Update(){
var x = transform.position.x;
var y = transform.position.y;
if (IsFollowing) {
if (Mathf.Abs (x - player.position.x) > Margin.x) {
x = Mathf.Lerp (x,player.position.x,smoothing.x*Time.deltaTime);
}
if (Mathf.Abs (y - player.position.y)> Margin.y) {
y = Mathf.Lerp (y,player.position.y,smoothing.y*Time.deltaTime);
}
}
float orthographicSize = GetComponent<Camera> ().orthographicSize;
var cameraHalfWidth = orthographicSize * ((float)Screen.width / Screen.height);
x = Mathf.Clamp (x,_min.x+cameraHalfWidth,_max.x-cameraHalfWidth);
y = Mathf.Clamp (y,_min.y+orthographicSize,_max.y-orthographicSize);
transform.position = new Vector3 (x,y,transform.position.z);
}
}