I am trying to Teleport a character from a Edge of the screen to the contrary edge I'm using this:
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.");
this work perfectly but the problem is that it teleport the character to the center and when I change the value to make it teleport to the edges it don't work correctly
The issue is that you transform a world coordinate ( transform.position
) to viewport space, do some changes, but never transform back from viewport space to worldspace before you apply it to 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.