我正在尝试将一个角色从屏幕的边缘传送到相反的边缘,我正在使用它:
var pos: Vector3 = Camera.main.WorldToViewportPoint(transform.position);
if (pos.x < 0.0) {
pos = new Vector3(0.0, 0.0, 0.0);
transform.position = pos;
//Debug.Log("I am left of the camera's view.");
}
if (1.0 < pos.x) {
pos = new Vector3(0.0, 0.0, 0.0);
transform.position = pos;
// Debug.Log("I am right of the camera's view.");
}
if (pos.y < 0.0) Debug.Log("I am below the camera's view.");
if (1.0 < pos.y) Debug.Log("I am above the camera's view.");
这项工作非常完美,但问题在于它将角色传送到中心,当我更改值以使其传送到边缘时,它无法正常工作
答案 0 :(得分:2)
问题是您将世界坐标(transform.position
)转换为视口空间,进行一些更改,但在将其应用于transform.position
之前,永远不会从视口空间转换回世界空间。
//you get a world space coord and transfom it to viewport space.
Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
//everything from here on is in viewport space where 0,0 is the bottom
//left of your screen and 1,1 the top right.
if (pos.x < 0.0f) {
pos = new Vector3(1.0f, pos.y, pos.z);
}
else if (pos.x >= 1.0f) {
pos = new Vector3(0.0f, pos.y, pos.z);
}
if (pos.y < 0.0f) {
pos = new Vector3(pos.x, 1.0f, pos.z);
}
else if (pos.y >= 1.0f) {
pos = new Vector3(pos.x, 0.0f, pos.z);
}
//and here it gets transformed back to world space.
transform.position = Camera.main.ViewportToWorldPoint(pos);