坐标系
World Space
Local Space
Screen Space
Viewport Space
坐标转换
Local Space --> World Space
注意三者的区别
World Space --> Local Space
World Space <–> Screen Space
World Space <–> Viewport Space
练习:判断物体的屏幕坐标
1.如果超过屏幕左侧或右侧,停止运动
2.上进下出,下进上出。
注意:此处使用屏幕坐标限制条件判断是由于Game面板的屏幕宽高比有多种形式,而若使用世界坐标,每次修改屏幕宽高比,限制条件都需要改变。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
///
/// </summary>
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 10;
private Camera mainCamera;
private void Start()
{
mainCamera = Camera.main;
}
private void Update()
{
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
if (hor != 0 || ver != 0)
Movement(hor, ver);
}
private void Movement(float hor, float ver)
{
hor *= moveSpeed * Time.deltaTime;
ver *= moveSpeed * Time.deltaTime;
//世界坐标转换为屏幕坐标
Vector3 ScreenPoint = Camera.main.WorldToScreenPoint(this.transform.position);
//(1)如果超过屏幕左侧或右侧,停止运动
//如果到了最左边,并且还想向左移动或者到了最右边,还想向右移动。
if (ScreenPoint.x <= 0 && hor < 0|| ScreenPoint.x >= Screen.width && hor > 0)
{
hor = 0;
}
//(2)下进上出,上进下出
if (ScreenPoint.y < 0)
ScreenPoint.y = Screen.height;
if (ScreenPoint.y > Screen.height)
ScreenPoint.y = 0;
//屏幕坐标转为世界坐标
this.transform.position = mainCamera.ScreenToWorldPoint(ScreenPoint);
transform.Translate(hor, 0, ver);
}
}