Restrict game characters from moving out of the screen

Restrict game characters from moving out of the screen

……

……

When playing games.

Be it a character or an enemy.

most of the time.

We need to keep character enemies on-screen so the player can see them and the player experience will be better.

so.

It is necessary to restrict the movement of game characters.

 

As shown in FIG.

Inside Start.

The first is to call the main camera, and use the main camera to convert the viewport coordinates into world coordinates.

The first Vector3, the two 0s in front refer to the lower left corner of the screen, and the 61.8f refers to the distance between the game character and the camera.

With this method, the world coordinates corresponding to the lower left corner and upper right corner of the plane where the game character is located can be obtained.

Next, you can use this world coordinate to limit the movement.

There is a very useful method, as follows:

Inside Update.

 

Clamp method, a total of three parameters. The first parameter is value, the second parameter is the minimum value, and the third parameter is the maximum value.

To give a very simple example, if the minimum value is 0 and the maximum value is 100. (If the value is 20, the result of 20 will be returned; if the value is -10, the result of 0 will be returned; if the value is 233, the result of 100 will be returned)

It can be seen that Clamp is purely used to limit the value of value, so that the minimum value is returned when the value is less than the minimum value, the maximum value is returned when it is greater than the maximum value, and value is returned if it is between the maximum value and the minimum value.

In this way, the position of the character can always be locked within the bounds of the screen.

……

……

Guess you like

Origin blog.csdn.net/oyqho/article/details/129942613