Why the shake down?

I think I followed the code in the video exactly, at least I can’t find any typos. My enemy ships scoot a little to the right then shake. Here’s my code

           using UnityEngine;
           using System.Collections;


           public class EnemySpawner : MonoBehaviour {
       public float EnemySpeed = 5;
        public GameObject enemyPrefab;
       public float width = 10f;
       public float height = 5f;
       private bool movingRight = true;
       private float xmax;	
       private float xmin;	
       // Use this for initialization
       void Start () {
	float distanceToCamera = transform.position.z - Camera.main.transform.position.z;
	Vector3 leftBoundary = Camera.main.ViewportToWorldPoint(new Vector3(0,0,distanceToCamera));
	Vector3 rightBoundary = Camera.main.ViewportToWorldPoint(new Vector3(1,0,distanceToCamera));
	xmax = leftBoundary.x;
	xmin = rightBoundary.x;
	
	foreach( Transform child in transform){
		GameObject enemy = Instantiate(enemyPrefab, child.transform.position, Quaternion.identity) as GameObject;
		enemy.transform.parent = child.transform;
		//the previous line makes sure the enemy spawns where this is
		
	}
}


public void OnDrawGizmos(){
Gizmos.DrawWireCube(transform.position, new Vector3(width,height));
}


void Update(){
	if(movingRight){
		transform.position += Vector3.right * EnemySpeed*Time.deltaTime;
	}
	else if (!movingRight){
		transform.position += Vector3.left * EnemySpeed*Time.deltaTime;
	}
float rightEdgeOfFormation = transform.position.x+(0.5f*width);
float leftEdgeOfFormation = transform.position.x-(0.5f*width);
if(rightEdgeOfFormation < xmin || leftEdgeOfFormation > xmax){
movingRight = !movingRight;
	}
   }

    }

I figured it out. I had two problems. First I swapped rightBoundary and leftBoundary. Second, my version didn’t like what he did here

if(leftEdgeOfFormation < xmin || rightEdgeOfFormation > xmax){

Instead I used the following and it worked.

if((leftEdgeOfFormation < xmin && !movingRight) || (rightEdgeOfFormation > xmax && movingRight))

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.