I’ve run into a small problem where for some reason bodies attached to one of my own Sprite classes seem to be added to a different world than the one my scene is using…
First, create a physics scene, (add a floor at the bottom if you want things to stay on screen).
World setup (in scene’s onEnter function):
auto physWorld = Director::getInstance()->getRunningScene()->getPhysicsWorld();
physWorld->setGravity(Vec2(0, -2200));
physWorld->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
physWorld->setSubsteps(3);
Add a key listener so you easily can spawn new objects, put this code in it.
if (key == EventKeyboard::KeyCode::KEY_SPACE)
{
auto org = Director::getInstance()->getVisibleOrigin();
auto screen = Director::getInstance()->getVisibleSize();
auto rad = 60.0f;
auto circle = Node::create();
auto circleBody = PhysicsBody::createCircle(rad);
circle->addComponent(circleBody);
circle->setPosition(RandomHelper::random_real(org.x + screen.width * 0.5, org.x + screen.width * 0.5 + 3), screen.height * 0.9);
addChild(circle);
auto c = Circle::init(RandomHelper::random_real(org.x + screen.width * 0.5, org.x + screen.width * 0.5 +3 ), screen.height * 0.9);
auto cBody = PhysicsBody::createCircle(60);
c->addComponent(cBody);
addChild(c);
}
Circle.h
#pragma once
#include "cocos2d.h"
using namespace cocos2d;
class Circle : public Sprite
{
Circle();
virtual ~Circle();
public:
static Circle* init(float x = 0, float y = 0);
};
Circle.cpp
#include "cocos2d.h"
#include "Circle.h"
Circle::Circle(void)
{
}
Circle::~Circle(void)
{
}
Circle* Circle::init(float x, float y)
{
auto sprite = new Circle();
if (sprite) {
float cRadius = 60.0f;
auto drawNode = DrawNode::create();
drawNode->drawSolidCircle(Vec2(x, y), cRadius, 0, 8, 1, 1, Color4F::BLACK);
sprite->addChild(drawNode);
sprite->autorelease();
return sprite;
}
CC_SAFE_DELETE(sprite);
return sprite = nullptr;
}
The bodies attached to the Circle class objects does not collide with anything in the scene’s physics world, neither the floor or the other “node” circles, but it’s clear that there IS a body because they’re falling down… if you know what’s going on, please help.
