- Home /
ViewportToWorldPoint causing object to move
I'm trying to lock my player ship object in camera's view, here's the code:
Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
pos.x = Mathf.Clamp(pos.x, 0, 1);
pos.y = Mathf.Clamp(pos.y, 0, 1);
transform.position = Camera.main.ViewportToWorldPoint(pos);
When converting back to worldspace coordinates there is misscalculation; upon every update small values are added to x-axis and substracted from y-axis. It is visible when object is idle. Ship is child of camera roatated by 90 degrees on x-axis.
Answer by superluigi · Jan 05, 2014 at 10:49 PM
Okay I'm a little confused but I'll try to help. I'm not sure if your camera is moving. I'm assuming your making a level like space invaders. Usually what you wanna do with this type of game is keep the camera still, give the player limited movement inside the cameras viewport, and have your background and enemies move down. I'm also going to assume you are running this level in the x and y axis.
var xpos : float = 5; var ypos : float = 5;
function Update()
{
transform.position.x = Mathf.Clamp(transform.position.x, -xpos, xpos);
transform.position.y = Mathf.Clamp(transform.position.y, -ypos, ypos);
}
This will work the way you want it however it's not using camera.viewporttoworldpoint. What you want to do is adjust xpos and ypos until it reaches the edge of the screen. This is just a much easier way, at least in my opinion. If you want to use viewportworlpoint let me know and I'll try to help you code that too.
Your answer
![](https://koobas.hobune.stream/wayback/20220613125456im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
WorldToViewportPoint and ViewportToWorldPoint math 2 Answers
Camera.ViewportToWorldPoint giving different values 0 Answers
Keeping field of view the same in a 2d game 0 Answers
Outside game clear screen 0 Answers