Turn at the edge
Read an if and else-if pair that reverses a patrol only when it is moving past a bound.
On this page
Touching an edge is not enough to turn. EnemyPatrol.FixedUpdate also checks which way the enemy is moving, so it does not flip back and forth while resting on a boundary.
The problem
Section titled “The problem”A patrol moves between left and right X bounds. At the left edge it should face right only if it was traveling left. At the right edge it should face left only if it was traveling right. Every other frame keeps the current direction.
When to reach for it
Section titled “When to reach for it”- Two conditions are mutually exclusive and order matters.
- The second check should run only when the first check is false.
- A default route should continue without changing the decision value.
See it
Section titled “See it”
The current Platformer source is:
private void FixedUpdate(){ var position = _rigidbody.position;
// Reverse when reaching a bound, but only if currently heading further past it, so the // enemy cannot get stuck flip-flopping on the boundary line. if (position.x <= _leftBoundX && _direction < 0) { _direction = 1; } else if (position.x >= _rightBoundX && _direction > 0) { _direction = -1; }
var velocity = _rigidbody.linearVelocity; velocity.x = _direction * _patrolSpeed; _rigidbody.linearVelocity = velocity;}-
Open
EnemyPatrol.FixedUpdatein Graph View. -
Read the
positionlocal. It copies the rigidbody position once so both bound checks use the same physics-step value. -
Follow the first branch. Its condition combines
position.x <= _leftBoundXwith_direction < 0. True sets_directionto1. -
Follow the false output into the second branch. This is the
else if:position.x >= _rightBoundXand_direction > 0. True sets_directionto-1. -
Follow all routes to the velocity sequence. The method copies current velocity, changes only its X component, then writes the struct value back to the rigidbody.
What it writes
Section titled “What it writes”Adding one shared step after the if and else-if, such as orienting the transform from the chosen direction, belongs after both branches join:
Putting that step inside only one branch would skip it on the other turn and on ordinary movement frames.
When it goes wrong
Section titled “When it goes wrong”When it goes wrong
| Symptom | Check | Fix |
|---|---|---|
| The enemy jitters at a bound. | Read whether each position check also tests direction. | Require movement past that same edge before changing direction. |
| Both edge checks run independently. | Follow the false output of the first branch. | Connect the right-edge check as else-if on that false route. |
| Vertical velocity disappears. | See whether the code replaces the whole velocity or only velocity.x. | Read current velocity, change X, and write the struct back. |
- Branch: build if and else-if routes.
- Get and set: read and write
_directionand velocity. - Operators and expressions: combine comparisons with Boolean operators.