坦克类定义及相关函数

 

#include <SFML/Graphics.hpp>
#define TANK_WEIGHT 50
#define TANK_HEIGHT 50
#define TANK_VELOCITY sf::Vector2f(0.0,-1.0)
#define TO_RADIAN * 3.1415926f / 180
class Tank : public sf::RectangleShape

{
public:
Tank() :RectangleShape(sf::Vector2f(TANK_WEIGHT, TANK_HEIGHT))
{
this->setPosition(400, 570);
this->setOrigin(TANK_WEIGHT / 2, TANK_HEIGHT / 2);
this->velocity = TANK_VELOCITY;
}
public:
void forward();
void stop_forward();
void back();
void stop_back();
void clockwise();
void stop_clockwise();
void anti_clockwise();
void stop_anti_clockwise();
void speedup();
void stop_speedup();
public:
//sf::Vector2f intersects(Obstacle &);
//Bullet fire();float getRadius();

void update(sf::Time elapsed, float width, float height);
private:
float tank_speed = 200.f;
bool forwarding = false;
bool backing = false;
bool clockwising = false;
bool anti_clockwising = false;
sf::Vector2f velocity;
};

 团队使用sfml框架,Tank类继承自sf::Vector2f,新添属性tank_speed,forwarding,backing,clockwising,anti_clockwising,velocity。键盘响应世间来实现改变坦克属性的值。

void move_tank(sf::Event &event, Tank &tank)
{
	if (event.type == sf::Event::KeyPressed)
	{
		switch (event.key.code)
		{
		case sf::Keyboard::Up:
			tank.forward();
			break;
		case sf::Keyboard::Down:
			tank.back();
			break;
		case sf::Keyboard::Left:
			tank.clockwise();
			break;
		case sf::Keyboard::Right:
			tank.anti_clockwise();
			break;
		case sf::Keyboard::Space:
			tank.speedup();
			break;
		default:
			break;
		}
	}
	if (event.type == sf::Event::KeyReleased)
	{
		switch (event.key.code)
		{
		case sf::Keyboard::Up:
			tank.stop_forward();
			break;
		case sf::Keyboard::Down:
			tank.stop_back();
		case sf::Keyboard::Left:
			tank.stop_clockwise();
			break;
		case sf::Keyboard::Right:
			tank.stop_anti_clockwise();
			break;
		case sf::Keyboard::Space:
			tank.stop_speedup();
			break;
		default:
			break;
		}
	}
}

  使用void update(sf::Time elapsed, float width, float height)函数来计算下一次刷新的坐标位置(X,Y)和坦克的朝向姿态即坦克的速度矢量方向。

 

犯得一些低级但耗费了时间的错误:window.display()函数位置不对导致窗口无显示;switch语句中的一个case少写了case语句,导致按下DOWN键相当于同时按下DOWN和LEFT键;图片后缀名写错,VS报无法打开PDB什么很高级的错误,查了一圈也没解决,出去转悠了一圈回来一眼看到就解决了,所以打开文件的操作一定要写错误检测,当然能考虑到出错的地方都应该想办法增加健壮性。

存在问题:坦克与边界碰撞偷懒近似成圆用半径算的,这会导致坦克沿x轴或沿y轴走到边界时扔距离边界有距离时就认为到达边界(因为半径比长或宽的一半都大)。

 
posted @ 2016-11-06 00:18  JokerMan  阅读(519)  评论(0编辑  收藏  举报