Moving Enemies
Creating a basic moving enemy
I created a basic enemy class child of the game object class in the Ex-Machina game. This class made the gameobject move backwards and forwards between two waypoints. If this class’s physics component’s mass was > 0 then it moved between the waypoints on the ground using the same momentum physics of the player. Otherwise, it was assumed a flying enemy and instead would lerp position between the two waypoints in the air. For both of these cases if the enemy collided with a block it would set the waypoint it was moving to the point where it collided and move to that point from now on. This code is also used to create moving blocks.
Momementum movement code
setPhysicsWaypoints(in_left, in_right, sprite); enemy_physics->setMomentumChange(ParameterChange::INCREASE); float spawn_dist = 1; if (start_waypoint.x < end_waypoint.x) { if (sprite->xPos() < start_waypoint.x) { current_vel.setX(base_velocity.getX()); sprite->xPos(start_waypoint.x + spawn_dist); enemy_physics->setMomentumChange(ParameterChange::STOP); } else if (sprite->xPos() > end_waypoint.x) { current_vel.setX(-base_velocity.getX()); sprite->xPos(end_waypoint.x - spawn_dist); enemy_physics->setMomentumChange(ParameterChange::STOP); } } else if (start_waypoint.x > end_waypoint.x) { if (sprite->xPos() > start_waypoint.x) { current_vel.setX(-base_velocity.getX()); sprite->xPos(start_waypoint.x - spawn_dist); enemy_physics->setMomentumChange(ParameterChange::STOP); } else if (sprite->xPos() < end_waypoint.x) { current_vel.setX(base_velocity.getX()); sprite->xPos(end_waypoint.x + spawn_dist); enemy_physics->setMomentumChange(ParameterChange::STOP); } }
Lerp Movement Code
if (x_move) { sprite->xPos(lerp_timer.lerp(start_waypoint.x, end_waypoint.x, x_lerp_percent)); horizontalLerpMovement(dt_sec); } if (y_move) { sprite->yPos(lerp_timer.lerp(start_waypoint.y, end_waypoint.y, y_lerp_percent)); verticalLerpMovement(dt_sec); }