一、屏幕坐标
世界坐标:transform.position,该物体在世界空间中的坐标
屏幕坐标:通过屏幕观察,该物体在屏幕上的位置。
屏幕坐标即主摄像机观察到的坐标,为Unity运行时出现的蓝色区域,y轴向上,x轴向右,左下角为(0, 0),宽度:Screen.width,高度:Screen.height,单位是像素。
int screenH = Screen.height;
int screenW = Screen.width; //大小可变,取决于窗口的实际大小。
Debug.Log("屏幕:" + screenH + "," + screenW);
获取一个物体的屏幕坐标:Camera.main.WorldToScreenPoint(worldPositon)
Vector3 worldPositon = transform.position;
Vector3 screenPositon = Camera.main.WorldToScreenPoint(worldPositon);
Debug.Log("世界坐标:" + worldPositon);
Debug.Log("屏幕坐标:" + screenPositon);
输出:
世界坐标:(5.0, 3.0, 0.0)
屏幕坐标:(491.5, 256.8, 10.0)
二、屏幕边界
从世界坐标来看,屏幕上限+5,下限-5,左右宽度不确定,具体的可视范围,由屏幕的实际长宽比决定。因此,当物体左右运动,要判断是否超出屏幕边界时,应当用屏幕坐标来判断。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyJet : MonoBehaviour
{
private float speed = 1.6f;
private bool toRight = true;
void Start()
{
transform.eulerAngles = new Vector3(0, 0, -90);
}
void Update()
{
Vector3 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (toRight && screenPosition.x > Screen.width)
{
toRight = false;
transform.eulerAngles = new Vector3(0, 0, 90);
}
if (!toRight && screenPosition.x < 0)
{
toRight = true;
transform.eulerAngles = new Vector3(0, 0, -90);
}
transform.Translate(0, speed * Time.deltaTime, 0);
}
}
|