My goal is to move the enemy formation down each time they “bounce” off the side, i.e. change direction. When testing, the formation does move down, but sometimes they jump down several steps instead of a single step. I am using a bool “drop” to flag if the formation changes direction, and an integer “bounces” to count the number of direction changes.
I am seeing weird things in the console messages as well. I am logging a message whenever I set drop as true and whenever bounces is incremented. The later is only executed in an if statement that checks if drop is true, so they should always be logged in pairs. However, in the console I only get the message for drop twice (followed by the bounces increment message), but after that I continue to get additional messages that bounce is being incremented. And sometimes it will increment bounces 2 or 3 times on direction change.
Here’s the code:
void Update() {
bool drop = false;
//Flip direction if enemy ship is near edge
foreach (Transform child in transform) {
if (child.transform.position.x > xmax - padding) { //statements execute if enemy postion is inside padding on rights side
if (direction == Vector3.right) { //additonally check if we are currently moving right
drop = true; Debug.Log("Drop");
}
direction = Vector3.left;
break;
}
else if (child.transform.position.x < xmin + padding) {
if (direction == Vector3.left) { drop = true; Debug.Log("Drop"); }
direction = Vector3.right;
drop = true;
break;
}
}
//Move the enemy formation horizontally each frame
transform.position += direction * speed * Time.deltaTime;
//Move the enemy formation down after direction change
if (drop) {
Debug.Log(bounces);
bounces++;
transform.position = new Vector3 (transform.position.x, transform.position.y -(bounces * dropDistance), transform.position.z);
drop = false;
}
Here is what the console looks like. The “5” and “6” occurred simultaneously, otherwise all of the drop increments happened individually when the formation changed direction. I am really puzzled as to why the “Drop” message stops after the 2nd time. This happens consistently.