2021-03-16 矩形的碰撞
程序员文章站
2022-03-13 14:36:53
...
#矩形的碰撞#
头文件
#ifndef _RECTANGLE_H_
#define _RECTANGLE_H_
class CRctangle
{
public:
CRctangle();
CRctangle(float Leftx, float Lefty, float rightx, float righty);
bool Collision(CRctangle rctangle);//碰撞函数
~CRctangle();//析构函数
private:
float m_LeftTopX;
float m_LeftTopY;
float m_RightBottomX;
float m_RightBottomY;
};
#endif
矩形cpp文件,实现矩形是否碰撞。
原理:矩形的中心点距离与两矩形长或宽的一半之和比较。
#include"Rectangle.h"
#include<iostream>
using namespace std;
CRctangle::CRctangle()
{
m_LeftTopX ;
m_LeftTopY ;
m_RightBottomX;
m_RightBottomY;
//cout << "调用了构造函数" << endl;
}
CRctangle::CRctangle(float Leftx, float Lefty, float rightx, float righty)
{
//求两个矩形的中心点,求其距离,与两矩形的宽一半(长)之和比较
m_LeftTopX = Leftx;
m_LeftTopY = Lefty;
m_RightBottomX = rightx;
m_RightBottomY = righty;
}
CRctangle::~CRctangle(){
//cout << "调用析构函数" << endl;
}
bool CRctangle::Collision(CRctangle rctangle)
{
float centerx = (m_LeftTopX + m_RightBottomX) / 2;
float centery = (m_LeftTopY + m_RightBottomY) / 2;
float centerx1 = (rctangle.m_LeftTopX + rctangle.m_RightBottomX) / 2;
float centery1 = (rctangle.m_LeftTopY + rctangle.m_RightBottomY) / 2;
if ((centerx - centerx1)*(centerx - centerx1) + (centery - centery1)*(centery - centery1) <= (m_LeftTopX - rctangle.m_RightBottomX)*(m_LeftTopX - rctangle.m_RightBottomX) || (centerx - centerx1)*(centerx - centerx1) + (centery - centery1)*(centery - centery1) <= (m_LeftTopY - rctangle.m_RightBottomY)*(m_LeftTopY - rctangle.m_RightBottomY))
{
return true;
}
else
{
return false;
}
}
这里是主函数入口,创建矩形对象,并对它赋值。
#include<iostream>
#include"Rectangle.h"
using namespace std;
int main()
{
CRctangle *p = new CRctangle(1, 2, 3, 4);
CRctangle *p1 = new CRctangle(1, 2, 3, 4);
// 创建对象,与上面两个无关
CRctangle rctangle;
p->Collision(*p1);
if (1 == p->Collision(*p1))
{
cout << "两个矩形碰撞" << endl;
}
else
{
cout << "两个矩形不碰撞" << endl;
}
delete p1;
p1 = nullptr;
delete p;
p = nullptr;
return 0;
}