从屏幕边缘传送角色到屏幕边缘
Teleporting Character From Edge to Edge of the Screen
我正在尝试将角色从屏幕的边缘传送到相反的边缘我正在使用这个:
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.");
这很好用,但问题是它将角色传送到中心,当我更改值使其传送到边缘时它不能正常工作
问题是您将世界坐标 (transform.position
) 转换为视口 space,进行一些更改,但永远不会从视口 space 转换回世界坐标 space 在将其应用于 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);
我正在尝试将角色从屏幕的边缘传送到相反的边缘我正在使用这个:
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.");
这很好用,但问题是它将角色传送到中心,当我更改值使其传送到边缘时它不能正常工作
问题是您将世界坐标 (transform.position
) 转换为视口 space,进行一些更改,但永远不会从视口 space 转换回世界坐标 space 在将其应用于 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);