2021-03-16 矩形的碰撞

#矩形的碰撞#

头文件

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gxy_w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值