如何设置恒速速度? (的Cocos2D-x)的

时间:2016-04-24 17:03:43

标签: cocos2d-iphone cocos2d-x

如何将速度设定为常数

spriteBody-> setVelocity(VEC2(100300)); 一段时间后这会慢下来

2 个答案:

答案 0 :(得分:1)

有许多解决方案可满足您的需求。您可以使用操作移动:

auto action = MoveBy::create (duration, Vec2(100,300));
spriteBody->runAction (action);

如果您想稍后停止:

sprite->stopAction (action);

您可以在更新功能中手动控制速度:

void update (float dt)
{
    //slow down speed
    //velocityVector is a Vec2 of velocity
    //slowAmount is a float which contains amount to slow in 1 second
    unitVector = velocityVector;
    unitVector.normalise();
    velocityVector -= unitVector *  slowAmount * dt;

    //adjust position
    sprite->setPosition (getPosition () + velocityVector * dt);
}

或者你可以使用物理身体:

sprite->getPhysicsBody()->applyForce(Vec2(100, 300));

如果您希望物理体减速,请为物理体设置材料的摩擦力

auto material = PHYSICSBODY_MATERIAL_DEFAULT; 
material.density = 1.0f;
material.restitution = 0.7f;
material.friction = 0.5f; //set friction here
sprite->setPhysicsBody(PhysicsBody::createBox(sprite->getContentSize(), material));

有关如何处理物理和设置的更多细节: http://www.cocos2d-x.org/wiki/Physics

答案 1 :(得分:0)

这是一个不断移动的球示例:

// Layer::init()
// center is just winSize / 2

auto ball = Node::create();
ball->setPosition(center);
auto circleBody = PhysicsBody::createCircle(10.f, PhysicsMaterial(1.f, 1.f, 1.f));
ball->setPhysicsBody(circleBody);
circleBody->setGravityEnable(false);
// change the direction so we don't keep watching it bouncing at the same direction up and down
circleBody->setVelocity(center + Vec2(500, 500));
this->addChild(ball);


void GameScene::update(float dt) {

    auto body = ball->getPhysicsBody();

    float constantSpeed = 500.f;

    body->setVelocity(body->getVelocity().getNormalized() * constantSpeed);
}
无论如何,这样做都会保持恒定的速度!