cocos3.15 完整代码在这
#include “HelloWorldScene.h”
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// ‘scene’ is an autorelease object
auto scene = Scene::createWithPhysics();
//test
scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on “init” you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto box = PhysicsBody::createEdgeBox(visibleSize, PHYSICSSHAPE_MATERIAL_DEFAULT, 3.0f);
auto sharpe = Node::create();
sharpe->setPhysicsBody(box);
sharpe->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
addChild(sharpe);
auto blockbody = PhysicsBody::createBox(Size(55,35));
blockbody->setDynamic(false);
auto blocksprite = Sprite::create("block.png");
blocksprite->setPosition(300, 200);
blocksprite->setPhysicsBody(blockbody);
addChild(blocksprite);
auto hero = Sprite::create("hero_item_ari.png");
hero->setPosition(300, 100);
hero->setTag(1);
addChild(hero);
auto herobody = PhysicsBody::createBox(Size(123,125));
hero->setPhysicsBody(herobody);
herobody->setCategoryBitmask(0x01); //0001
herobody->setContactTestBitmask(0x01); //0001
herobody->setCollisionBitmask(0x01); //0011
blockbody->setCategoryBitmask(0x01); //0010
blockbody->setContactTestBitmask(0x01); //0011
blockbody->setCollisionBitmask(0x01); //0001
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [&](Touch* touch,Event* event)
{
this->getChildByTag(1)->getPhysicsBody()->setVelocity(Vec2(0,100));
return true;
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
auto physicslistener = EventListenerPhysicsContact::create();
physicslistener->onContactBegin = [](PhysicsContact& contact)
{
CCLOG("onContactBegin");
return false;
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(physicslistener, this);
return true;
}