Sprite random movement

ghost1callback = CallFunc::create([this]()
	{
		ghost1random1 = cocos2d::RandomHelper::random_int(1, 100);
		ghost1random2 = cocos2d::RandomHelper::random_int(1, 100);
	});

	ghost1sequence = Sequence::create(ghost1callback, MoveTo::create(5, Vec2(visibleSize.width*ghost1random1 / 100, visibleSize.height*ghost1random2 / 100)), NULL);
	ghost1wander = RepeatForever::create(ghost1sequence);
	ghost1->runAction(ghost1wander);

What am I doing wrong here? The random variables change constantly but the sprite doesn’t move to the new point location.

it’s because ghost1callback will be called after this calculation

MoveTo::create(5, Vec2(visibleSize.width*ghost1random1 / 100, visibleSize.height*ghost1random2 / 100))

Why you need this callback?
Can you just generate random numbers before?

I got rid of the callback and I am generating random numbers in my update function. It still doesn’t work.

Try this idea:

  1. generate random position
  2. runAction with sequence and callback at end of animation
  3. in callback do item 1 and 2

I’m not sure I understood correctly, but here is the code:

ghost1random1 = cocos2d::RandomHelper::random_int(1, 100);
	ghost1random2 = cocos2d::RandomHelper::random_int(1, 100);

	this->runAction(RepeatForever::create(wanderAnimate));

	callback = CallFunc::create([this]()
	{
		ghost1random1 = cocos2d::RandomHelper::random_int(1, 100);
		ghost1random2 = cocos2d::RandomHelper::random_int(1, 100);
		ghost1moveAction = MoveTo::create(5, Vec2(visibleSize.width*ghost1random1 / 100, visibleSize.height*ghost1random2 / 100));
		this->runAction(ghost1sequence);
	});

	ghost1sequence = Sequence::create(callback, NULL);
	this->runAction(ghost1sequence);

I’m getting the following error: https://i.imgur.com/uiMGwO4.png

I found this answer, but I have no knowledge whatsoever in objective c and I can’t translate it in c++.

Objective C isn’t that different from C/C++. Here’s the code in C++ (it does work):

void moveRandom(Sprite* s)
{
    auto randomPoint = Vec2(rand() % 480, rand() % 320);

    auto moveTo = MoveTo::create(rand() % 5 + 1, randomPoint);
    auto delayTime = DelayTime::create(0.5);
    auto moveAgainFunc = CallFunc::create([=]()
    {
        moveRandom(s);
    });

    auto actions = Sequence::create(moveTo, delayTime, moveAgainFunc, nullptr);

    s->runAction(actions);
}


Sprite* s = Sprite::create("yourImage.png");
this->addChild(s);
this->moveRandom(s);
3 Likes

Yes, this works, thank you.

Nice solution. I have marked it as such.