Making an object accelerate in opposite direction on input

I’m trying to get an object to accelerate along the x axis, and this is working for the most part but it doesn’t pick up the input half the time, and so the variable won’t switch causing the object to shoot off in one direction.

public class paddle_move : MonoBehaviour {

public float xaccel;
private float acceltotal = 0;

void Update () {

	acceltotal += xaccel;

	rigidbody2D. = rigidbody2D.velocity + new Vector2 (acceltotal, 0.0f);

	if (Input.anyKey) {
		xaccel *= -1;
	}
}

}

‘Input.anyKey’ return true for every frame the key is held down. So your value of xaccel will flip every frame. If you happen to hold the key down an odd number of frames, then it will switch at the end of the key press. If even number of frames, then it will stay the same.

Change ‘Input.anyKey’ to ‘Input.anyKeyDown’.