In online games we often see monsters moving mechanically back and forth, and here’s a way to do it.

(1) First, drag the image to the Hierarchy window and automatically create a gameObject named Monster (1).

(2) bind c# script to monster(1).

The script content is as follows:

The two Transform objects pos_left and pos_right are fixed gameObjects in the scene. Pos_left.position. x and pos_right.position.x get their X coordinates to set the monster left Right moving boundary. If the monster is beyond the left edge (the x-coordinate of the monster position is less than pos_left.position.x), the monster becomes right-facing (faceLeftfalse) and gives the monster a right-facing velocity (rb.Velocity = new) Vector2 (speed, rb. Velocity. Y)), Monster beyond the right boundary (monster position x greater than pos_right.position.x) the monster becomes left facing (faceLefttrue) and gives the monster a left facing velocity (rb.Velocity = new) Vector2 (-speed, rb. Velocity. Y)).

As shown in the figure above, there are two fixed POS_left and pos_right (objects in the hierarchy window are named fixed(3) and fixed(4)). Because they only limit the moving range of monsters, their pictures are very small and difficult to see.

Fixed (3) Fixed (4)/fixed(3)/fixed(4)

In this way, objects can be automatically moved left and right.