add a variable out=true; as default (type= boolean)
if(ox+w/2>oxmax)ox=oxmax-w/2;
if(out){
if(ox-w/2<oxmin && oy+h/2>oymin)oy=oymin;
if(ox-w/2>=oxmin && ox+w/2<=oxmax && oy+h/2>oymin)out=false;
}else{
if(ox-w/2<oxmin)ox=oxmin+w/2;
if(ox+w/2>oxmax)ox=oxmax-w/2;
if(oy+h/2>oymax)oy=oymax-h/2;
}