Question by 
               trobinson79 · Mar 13, 2021 at 10:17 PM · 
                2d gameai2d-platformerrigidbody2dcolliders  
              
 
              Enemy character floats while he moves back and forth
I'm trying to get my enemy in my 2D platformer to go left and right continuously. He does that, but then he floats at certain points on the map rather than traversing downward or upward on the map based on where the ground is going.
Nothing wrong with the rigidbody or collider as far as I can tell. Here's a screenshot of its settings:

And here's the code I have on him:
public class EnemyController : MonoBehaviour { private Vector2 initialPosition; private float direction; public float maxDist = 1.5f; public float minDist = 1.5f; public float movingSpeed = 2.0f;
 // Start is called before the first frame update
 void Start()
 {
     initialPosition = transform.position;
     direction = 1;
     maxDist += transform.position.x;
     Debug.Log(maxDist);
     minDist += transform.position.x;
     Debug.Log(minDist);
 }
 // Update is called once per frame
 void Update()
 {
     switch (direction)
     {
         case -1:
             // Moving Left
             if (transform.position.x > minDist)
             {
                 GetComponent<Rigidbody2D>().velocity = new Vector2(-movingSpeed, GetComponent<Rigidbody2D>().velocity.y);
             }
             else
             {
                 direction = 1;
                 GetComponent<Rigidbody2D>().transform.Rotate(new Vector3(0, -180, 0), Space.Self);
             }
             break;
         case 1:
             //Moving Right
             if (transform.position.x < maxDist)
             {
                 GetComponent<Rigidbody2D>().velocity = new Vector2(movingSpeed, GetComponent<Rigidbody2D>().velocity.y);
             }
             else
             {
                 direction = -1;
                 GetComponent<Rigidbody2D>().transform.Rotate(new Vector3(0, 180, 0), Space.Self);
             }
             break;
     }
 }
 
               }
 
                 
                unity-enemy-settings.png 
                (35.8 kB) 
               
 
              
               Comment
              
 
               
              Your answer