想做的是一个通过鼠标控制小球在屏幕中间弹跳的游戏,代码如下:
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
size = Director::getInstance()->getVisibleSize();
printf("size.width=%f, size.height=%f\n", size.width, size.height);
world = new b2World(b2Vec2(0, 0));
world->SetContactListener(this);
// addBackGround();
addEdge();
addBall();
// onEnter();
scheduleUpdate();
return true;
}
void HelloWorld::onEnter(){
printf("onEnter!\n");
Layer::onEnter();
this->setTouchEnabled(true);
}
void HelloWorld::update(float dt){
world->Step(dt, 8, 3);
for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()){
if(b->GetUserData() == sBall){
sBall->setPosition(b->GetPosition().x*RATIO, b->GetPosition().y*RATIO);
// printf("x=%f, y=%f\n", b->GetPosition().x, b->GetPosition().y);
}
}
}
void HelloWorld::onTouchesBegan(Touch *t, Event *e){
auto location = t->getLocationInView();
location = CCDirector::getInstance()->convertToGL(location);
auto locationWorld = b2Vec2(location.x/RATIO, location.y/RATIO);
printf("onTouchesBegin, locationWorld.x=%f, locationWorld.y=%f\n", locationWorld.x, locationWorld.y);
if(ball->GetFixtureList()->TestPoint(locationWorld)){
b2MouseJointDef md;
md.bodyA = ball;
md.bodyB = edgeBody;
md.target = locationWorld;
md.collideConnected = true;
md.maxForce = 1000.0f * ball->GetMass();
mouseJoint = (b2MouseJoint *)world->CreateJoint(&md);
flag = true;
printf("onTouchesBegin, I'm in!\n");
}
return;
}
void HelloWorld::onTouchesMoved(Touch *t, Event *e){
if(mouseJoint == NULL || flag == false) return;
auto location = t->getLocationInView();
location = CCDirector::getInstance()->convertToGL(location);
auto locationWorld = b2Vec2(location.x/RATIO, location.y/RATIO);
mouseJoint->SetTarget(locationWorld);
return;
}
void HelloWorld::onTouchesEnded(Touch *t, Event *e){
if(mouseJoint != NULL && flag == true){
world->DestroyJoint(mouseJoint);
mouseJoint = NULL;
flag = false;
}
return;
}
运行效果是无法响应触摸事件(即不能输出onTouchesBegin那的LOG), 在网上查了很多例子,没有看出有什么差别,希望得到大神的解答。