📄 wrapkeepdis.cpp
字号:
#include <airobot/cpp/SimpleRobot.hpp>
/**
* 围绕对手作来回的移动,并在此基础上添加了与对手保持一定距离的功能
* @author xiemin
*/
class WrapKeepDis : public SimpleRobot
{
private:
//理想距离
static const double PREFER_DISTANCE;
//在一个方向上最大的移动时间
static const long MAX_TIME;
//移动的方向,这个变量的值只能取1和-1,1表示前进,-1表示后退
int direction;
//当前在一个方向上的移动时间
long time;
public:
WrapKeepDis(void)
{
direction = 1;
time = 0;
}
void onTick(TickAction* action)
{
setDirection();
doMove();
doTurn();
}
private:
/**
* 设置移动的方向
*/
void setDirection(void)
{
time++;
if(time>MAX_TIME)
{
direction *= -1; //变换移动方向
time = 0;
}
}
/**
* 执行移动
*/
void doMove(void)
{
move(10*direction);
}
/**
* 执行转动
*/
void doTurn(void)
{
Point2D center = getCenter();
double lineHeading = Math::heading(getLocation(), center);
double headingTo = lineHeading + Math::PI/2;
//为了保持距离用deltaAngle对headingTo进行修正
double deltaAngle = getDeltaAngle(center);
headingTo -= deltaAngle;
//执行转动
double bearing = Math::bearing(headingTo, getHeading());
turn(bearing);
}
/**
* 得到用于保持理想距离的修正角deltaAngle
* @param center
* @return
*/
double getDeltaAngle(const Point2D& center)
{
double distance = Math::distance(center, getLocation());
double deltaDistance = distance-PREFER_DISTANCE;
deltaDistance = deltaDistance/Math::max(distance, PREFER_DISTANCE);
return direction*Math::PI/3*deltaDistance;
}
/**
* 得到圆心位置
*/
Point2D getCenter(void)
{
Bot* bot = getFirstOpponent();
if(bot!=NULL) return bot->getLocation();
else return Point2D(getCourtWidth()/2, getCourtHeight()/2);
}
};
const double WrapKeepDis::PREFER_DISTANCE = 300;
const long WrapKeepDis::MAX_TIME = 35;
//启动机器人程序
int main(int argC, char* argV[])
{
Robot* robot = new WrapKeepDis();
return startup(argC, argV, robot);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -