After Sora beat the crap out of Ansem SoD, it kind of knocked Riku back in to a state of control, or at least realization of what he had living inside of him. During CoM, his whole deal was learning to cope with the darkness inside of him and find a decent balance. Ansem the Wise (or DiZ) used Riku's passion for getting Sora back to normal to coax Riku into using the darkness inside of himself (the leftover Ansem SoD bits) to fight and capture Roxas, which in turn transformed his appearance to look like Xehanort's Heartless. Only in the end of KH2, when Ansem the Wise's machine blew up, did Riku turn back (because it had "Unexpected Side-effects).
Hope that helps!