Updated code with collision detection