Apparently, Onan having sex with Tamar (married her?) wasn't the right kind of sex. There is a much higher purpose according to God.
This is not just addressing you Cap. I’m just using this to jump off from.
This passage is showing one of the obligations of the kinsman redeemer from the earliest of times. Onan didn’t have to have a ceremony because he was filling the responsibilities of his brother who had married her already. By sleeping with her, he was fulfilling his brothers covenant to provide an heir. This is the only reason why God killed him for spilling his seed. Not because that is a sin, but because he was blaspheming the role he was modeling. Christ as the kinsman redeemer would never be deceitful.