To get pregnant, must you have sex right when ovulation occurs?

No. Both the egg and the sperm have some leeway here. The sperm can be viable for several days and the egg can be viable for 24 hours or more. If your looking to avoid pregnancy, err on caution and leave a pretty big window, if trying to concieve time it closer.