Hamlet really does present different sides of himself, depending on who he thinks is around. When he is by himself, he is ponderous, mopey, analytical, and philosophical. When he thinks that the king, queen, or Polonius are in the vicinity, he tends to put on his "antic disposition" act, behaving in bizarre, nonsensical, disrespectful ways. And, with trusted friends, which, by the end of the play is pretty much limited to Horatio, he is logical, kind and forthright.
Why the different acts? Well, the most "true" Hamlet is probably the one when he is by himself--we can trust what he says, because he's not trying to put on a show, throw anyone off, or act a part. When he shows different behaviors around the king, his mother, or around Polonius or Ophelia, he is trying to throw them off. He has been commanded to enact revenge on the king for the murder of his father, and has to go about investigating the situation. He figures he can investigate it most safely if he acts like his is crazy, and makes everyone around him think he's off his rocker. That way, if he does or says something that is suspiciously close to revealing he knows about the murder, the king won't be alarmed--he'll just think it's another one of Hamlet's nonsensical rants. He thinks that if no one takes him seriously, he can spy about without suspicion. Another reason he acts strangely, especially to Ophelia and his mother, is because he has lost all faith in women and their ability to be faithful and true to men. He thinks they are flirtatious and shallow; his mother has ruined his opinion of women. Her "o'er hasty" marriage to his uncle shocked him just as much as his father's death did. He is bitter about it, and so takes out his bitterness against Ophelia, who is a woman, and against his mother, who is the source of his angst.
Hamlet's an emotional guy with a lot of hang-ups, which accounts for many of his behavior shifts. He is also burdened with the weighty task of enacting revenge against an uncle that he isn't even sure is guilty yet. That is why Hamlet behaves in such different ways throughout the course of the play. I hope that those thoughts helped; good luck!