需求是这样的,游戏中常常需要在手机屏幕的左右边界各加一个碰撞体。效果就是角色撞到屏幕边缘被弹回之类的。但是屏幕的比例会变,因此需要写代码,让它们一直处于边界。
碰撞体如下:
代码也很简单:
using UnityEngine;
public class SideCollider : MonoBehaviour
{
[Header("border colliders --- ")]
public Transform leftBorderCollider;
public Transform rightBorderCollider;
[Header("half collider width --- ")]
public float halfColliderWidth = 0.5f;
// half screen width size
private float halfScreenWidth;
private void Start()
{
float halfSreenHeight = Camera.main.orthographicSize;
halfScreenWidth = Screen.width / (float)Screen.height * halfSreenHeight;
Debug.Log(halfScreenWidth);
//
leftBorderCollider.position = new Vector3(-halfScreenWidth - halfColliderWidth, leftBorderCollider.position.y, leftBorderCollider.position.z);
rightBorderCollider.position = new Vector3(halfScreenWidth + halfColliderWidth, rightBorderCollider.position.y, rightBorderCollider.position.z);
}
}