Every crime is different, so it is difficult to answer this question. What we can say is that criminal law in most legal traditions distinguishes, to varying degrees, between crimes committed by calculating, rational actors and those directly resulting from a mental illness on the part of the accused. Most people who have even a passing familiarity with the legal system—even if only through television and movies—are familiar with the plea "not guilty by reason of insanity." There are multiple aspects to this, but all generally have the same characteristics: the accused is not guilty if he or she was not able to control themselves at the time of the crime or if they were not able to understand the consequences of their actions, provided that these conditions are proven to be the result of some mental illness. So-called "crimes of passion" may result in a lesser sentence or even a lesser charge if it can be shown that the accused was acting out of irrational rage rather than calculated malicious intent.
On the other hand, there are individuals who commit calculated crimes based on a rational (if amoral) calculation that they will benefit from the crime. Indeed, the majority of so-called "white collar crime" falls in this category because the convicted knew what they were doing and that it was wrong. Violent, calculated crimes receive harsher sentences than those committed out of passion. First degree murder, for example, is usually willful and calculated. So, to repeat, people commit crimes for an array of reasons, and legal systems, especially as our understanding of the human mind expands, reflect this recognition.