您的位置:首页 > 移动开发 > Cocos引擎

cocos2d-x 3.2 物理小游戏教程2 block it 物理世界 墙壁

2015-09-13 21:47 483 查看
新建一个项目,创建一个GameScene.h和GameScene.cpp,可以仿照Helloworld.h和cpp

在GameScene.cpp创建场景的方法中做一点变动:

Scene* GameScene::createScene()

{

//创建物理世界场景

auto scene = Scene::createWithPhysics();

//获取物理世界

auto world = scene->getPhysicsWorld();

//设置物理世界重力

world->setGravity(Vect(0, 0));

//设置物理世界调试模式:显示全部

world->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);

auto layer = GameScene::create();

scene->addChild(layer);

return scene;

}

新建一个墙壁类Wall

Wall.h

#ifndef __WALL_H__

#define __WALL_H__

#include "cocos2d.h"

class Wall : public cocos2d::Sprite

{

public:

//创建方法 参数是图片路径

static Wall* create(const std::string& spriteFrameName);

bool init(const std::string& spriteFrameName);

private:

const float fadeTime = 0.1f;

bool canTouch = true;

};

#endif // !__WALL_H__

===================================================

Wall.cpp

#include "Wall.h"

USING_NS_CC;

Wall* Wall::create(const std::string& spriteFrameName)

{

Wall *pRet = new Wall();

if(pRet && pRet->init(spriteFrameName))

{

pRet->autorelease();

return pRet;

}

else

{

delete pRet;

pRet = NULL;

return NULL;

}

}

bool Wall::init(const std::string& spriteFrameName)

{

Sprite::initWithFile(spriteFrameName);

//创建矩形刚体

auto body = PhysicsBody::createBox(this->getContentSize());

//设置弹力

body->getShape(0)->setRestitution(1.02f);

//设置摩擦力

body->getShape(0)->setFriction(0.0f);

//设置是否受力旋转

body->setRotationEnable(false);

//设置是否受重力

body->setGravityEnable(false);

//设置是否静态 静态物体不会因为收到碰撞而改变位置

body->setDynamic(false);

//把精灵和物理刚体绑定

this->setPhysicsBody(body);

return true;

}

=======================================================

有了墙壁类 我们就可以仿照游戏创建上,左,右三面墙壁了

在GameScene.cpp

bool GameScene::init()

{

Layer::init();

vSize = Director::getInstance()->getVisibleSize();

//创建左侧墙壁

auto wallLeft = Wall::create("length.png");

wallLeft->setPosition(vSize.width * 0.1, vSize.height * 0.5);

this->addChild(wallLeft);

//创建上方墙壁

auto wallTop = Wall::create("width.png");

//根据左侧墙壁高度设置位置,把它盖在左侧墙壁的上方

wallTop->setPosition(vSize.width * 0.5, wallLeft->getBoundingBox().getMaxY() + wallTop->getContentSize().height / 2);

this->addChild(wallTop);

//创建右侧墙壁

auto wallRight = Wall::create("length.png");

wallRight->setPosition(vSize.width * 0.9, vSize.height * 0.5);

this->addChild(wallRight);

return true;

}

==============================================================

运行截图



红色的边框就是说明调试模式起作用,所有的刚体都会被红色的线绘制出来。

这一章内容就先介绍到这里,下一章讲介绍创建物理小球,触摸屏幕让小球运动起来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: