码迷,mamicode.com
首页 > 编程语言 > 详细

我的 Unity2D 屏幕适配

时间:2015-07-17 20:59:24      阅读:345      评论:0      收藏:0      [点我收藏+]

标签:

以下方法纯属我YY,切勿当真!!!

确定一个设计尺寸,比如 devWidth = 960,devHeight = 640, 按照这个尺寸进行设计游戏.

方式一: 不管什么屏幕尺寸,都和设计的尺寸对应.

只需在 Camera上 加上如下脚本:

 

public class ScreenAdapter : MonoBehaviour {

	private Camera mainCamera;

	private static float devWidth = 960f;
	private static float devHeight = 640f;
	private static float devAspect = devWidth / devHeight;

	// Use this for initialization
	void Start () {
		mainCamera = Camera.main;

		mainCamera.aspect = devAspect;
		mainCamera.orthographicSize = devHeight * 0.01f / 2;
	}
}

方式二:  只缩放背景图片.只需将如下代码放到背景上:

public class BgAdapter : MonoBehaviour {

	private Camera mainCamera;

	private static float devWidth = 960f;
	private static float devHeight = 640f;
	private static float devAspect = devWidth / devHeight;

	//  背景完全显示在屏幕上
	private bool mShowAll = true;

	// Use this for initialization
	void Start () {
		
		mainCamera = Camera.main;
		Vector3 scale = transform.localScale;

		float sy = mainCamera.orthographicSize * 2 * 100/ devHeight;
		float cameraWidth = mainCamera.orthographicSize * mainCamera.aspect * 2 * 100;
		if (mainCamera.aspect > devAspect) {
			
			// 会在左右留下空白,所以可以放大x
			float sx = cameraWidth/devWidth;
			scale.x = sx * sy;

			if (!mShowAll) {
				scale.y = scale.x;
			}
		
			transform.localScale = scale;

		} else if (mainCamera.aspect < devAspect) {

			if (mShowAll) {
				// 会裁减左右,所以可以进行缩小 x
				float sx = cameraWidth/devWidth;
				scale.x = sx * sy;

				transform.localScale = scale;
			}
		}
	}
}

  如果mShowAll为true,则进行适配的时候背景图片会进行不均匀的拉伸,但是图片不会被裁减掉

   如果mShowAll为false,则进行适配的时候背景图片可能进行的是均匀的拉伸,但是图片会被裁减掉.

Over!!!

 

           

我的 Unity2D 屏幕适配

标签:

原文地址:http://www.cnblogs.com/daihanlong/p/4655562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!