WSAD移动 有碰撞的话会显示一个原点
我用的是两张80*80的图片 用其他的图片的话自己改代码 把图片改名成1.png和 2.png
就是这两张图片
#include<graphics.h>
#include<windows.h>
#include<stdio.h>
int xx,yy;
int wanjiax=20,wanjiay=120;
SMALL_RECT z,f,naka;
bool panduan(PIMAGE img,PIMAGE img2)
{bool zf=0;if(wanjiay<=200) {zf=1;z.Left=wanjiax;z.Top=wanjiay;z.Right=wanjiax+80;z.Bottom=wanjiay+80;f.Left=100;f.Top=200;f.Right=180;f.Bottom=280;}else {zf=0;z.Left=100;z.Top=200;z.Right=180;z.Bottom=280;f.Left=wanjiax;f.Top=wanjiay;f.Right=wanjiax+80;f.Bottom=wanjiay+80;}//主副框赋值完成if(f.Top>z.Bottom||f.Right<z.Left||f.Left>z.Right||f.Bottom<z.Top) return 0;//排掉没有相交完成color_t *zh,*fh;if(f.Right<=z.Right) {//如果副框在框左边 包含中线naka.Left=z.Left;naka.Top=f.Top;naka.Right=f.Right;naka.Bottom=z.Bottom;for(int j=naka.Top;j<=naka.Bottom;j++){if(zf) {zh=getbuffer(img);fh=getbuffer(img2);}else {fh=getbuffer(img);zh=getbuffer(img2);}fh+=(j-naka.Top)*80;zh+=(j-z.Top)*80;fh+=(naka.Left-f.Left);for(int i=naka.Left;i<=naka.Right;i++,fh++,zh++){if((*zh)!=0&&(*fh)!=0) {xx=i;yy=j;return 1;}}}}else {//如果副框在框右边 不含中线naka.Left=f.Left;naka.Top=f.Top;naka.Right=z.Right;naka.Bottom=z.Bottom;for(int j=naka.Top;j<=naka.Bottom;j++){if(zf) {zh=getbuffer(img);fh=getbuffer(img2);}else {fh=getbuffer(img);zh=getbuffer(img2);}fh+=(j-naka.Top)*80;zh+=(j-z.Top)*80;zh+=(naka.Left-z.Left);for(int i=naka.Left;i<=naka.Right;i++,zh++,fh++){if((*zh)!=0&&(*fh)!=0) {xx=i;yy=j;return 1;}}}}
}
main()
{initgraph(640,480);PIMAGE img,img2;bool b=0;img=newimage();img2=newimage();getimage_pngfile(img2,"2.png");char ch;img=newimage();getimage_pngfile(img,"1.png");for(;is_run();delay_fps(60)) {clearviewport();if(panduan(img,img2)==1) {b=1;}else {b=0;xx=-10;yy=-10;}putimage_withalpha(NULL,img,wanjiax,wanjiay);putimage_withalpha(NULL,img2,100,200);setcolor(EGERGB(255,255,255));int a[]={wanjiax,wanjiay,wanjiax+80,wanjiay,wanjiax+80,wanjiay+80,wanjiax,wanjiay+80,wanjiax,wanjiay};drawpoly(5,a);int b[]={100,200,180,200,180,280,100,280,100,200};drawpoly(5,b);setcolor(EGERGB(69,255,0));int c[]={naka.Left,naka.Top,naka.Right,naka.Top,naka.Right,naka.Bottom,naka.Left,naka.Bottom,naka.Left,naka.Top};drawpoly(5,c);setcolor(EGERGB(255,255,255));if(b) {setfillcolor(EGERGB(255,255,255));fillellipse(xx,yy,5,5);}if(kbhit()) {ch=getch();switch(ch) {case 'a':wanjiax-=1;break;case 's':wanjiay+=1;break;case 'w':wanjiay-=1;break;case 'd':wanjiax+=1;break;case 'j':getch();break;}}}delimage(img);closegraph();return 0;
}
思路来源
“等一下,我碰!”——常见的2D碰撞检测 - Bill Yuan - 博客园 (cnblogs.com)