Limited movement on screen?

Hello, I’m developing a simple game in Unity 3D, just to study. The game is similar to Space Invaders and my doubt is about limiting the movement of the player by the screen area. What I mean is that when I use the transform.position he usually limits the movement, but in game, depending on the screen resolution, the limited space can vary.

Below is the code I tried to use to solve the problem.

var target : Transform;

function Start () {
}

function Update () {

var screenPos: Vector3 = Camera.main.WorldToViewportPoint(target.position);
print(screenPos);

if(screenPos.x >= 1)
	{
	screenPos.x = 1; 
	}
}

In my view this should work, but do not understand why that does not work, please help me!

Please format your code, I'm not even going to bother reading the question, if the code isn't formatted

I would need more information about the problem to understand what you are asking. So on lines 11 - 14 you make sure you have a viewport coordinate that is within the viewport on the right. What do you do with the coordinate? Do you convert it back to a world coordinate and set a position? Convert it to a screen coordinate and limit the movement of a GUI object?

1 Answer

1

I supposed that you are thinking of limiting the player’s 3D position using the camera field-of-view.

You have the right logic in limiting the x when it is larger than a certain value. However, limiting the screenPos will not affect the target.position. screenPos is a point in space that is computed from WorldToViewportPoint() using target.position. So, changing screenPos will not affect target.position.

You should do the following:

if( screenPos.x >= 1 ) {
   screenPos.x = 1;    
   target.position = Camera.main.ViewportToWorldPoint( screenPos.x );
}

But I have little experience in these issue, so I am not certain that the Vector3 used in ViewportToWorldPoint() and WorldToViewportPoint() are inter-convertible. What I am trying to say is:

position == Camera.main.ViewportToWorldPoint( Camera.main.WorldToViewportPoint( position ) )

If this statement is true, then you can use ViewportToWorldPoint() to re-convert the clamped screenPos back to target.position.