I am working on a script for an enemy in a platformer game.I want it to move a specific distance left or right and then return to the origin and just to do the same thing.
please show me a way to script this thing.I already tried but can’t figure out the conditions.(In my script I used 2 bool movingRight and movingLeft).
There’s loads of ways of doing something like that. A simple way would be to have 2 variables that define the minimum X position of the enemy and the maximum X position. You could also have an integer that is -1 when moving left and +1 when moving right.
e.g.
float fMinX = 50.0f;
float fMaxX = 250.0f;
int Direction = -1;
Update:
switch( Direction )
{
case -1:
// Moving Left
if( fEnemyX > fMinX )
{
fEnemyX -= 1.0f;
}
else
{
// Hit left boundary, change direction
Direction = 1;
}
break;
case 1:
// Moving Right
if( fEnemyX < fMaxX )
{
fEnemyX += 1.0f;
}
else
{
// Hit right boundary, change direction
Direction = -1;
}
break;
}
sprEnemy.transform.localPosition = new Vector3( fEnemyX , 0.0f , 0.0f );