1
\$\begingroup\$

I am having a difficulty and I am been doing it wrong, I think. I want to move sprite relatively to touch. Just like when you are playing space shooter like 1943. I just learning some math and try to mimic those control by myself but I have no luck doing so far.

I have snippet of code, its far from perfect, I was able to move the sprite relatively but keeps jumping off when I first touch and moved.

Here is what I got so far:

When the touch move:

void Trooper::onTouchMoved(cocos2d::Touch * touch, cocos2d::Event * event)
{
    mPreviousTouchPosition = mTouchMovePosition;
    mTouchMovePosition = touch->getLocation();

    cocos2d::Vec2 delta = utility::Object::getPosition() + (mTouchMovePosition - mPreviousTouchPosition);
    delta = utility::Object::getContainingScene()->convertToNodeSpace(delta);

    utility::Object::setPositionTo(delta);

    CCLOG("Coordinates when moved : %f , %f" , delta.x , delta.y);
}

Here is the data I logged and the first line for coordinates when moved seem anomalous to me:

Coordinates on touch : 633.746338 , 395.874329
Coordinates when moved : 883.746338 , 644.876404
Coordinates when moved : 882.747925 , 644.876404
Coordinates when moved : 880.752136 , 642.879517
Coordinates when moved : 878.755249 , 641.881104
Coordinates when moved : 876.758423 , 640.882690
Coordinates when moved : 874.761536 , 637.887939

I shouldn't be seeing this kind of huge number when my actual sprite is on 250 , 250. The difference of previous touch position and the current touch position should be added to the sprite position. I wanted to achieve relativeness regardless I touch and move. The sprite should mimic that. Did I missed something or anything wrong with my math?

Thank you!

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

My actual code actually works. I only forgot to initialize the mTouchMovedPosition initially to the mOnTouchPosition.

Here is what I have:

void Trooper::onTouchMoved(cocos2d::Touch * touch, cocos2d::Event * event)
{
    mPreviousTouchPosition = mTouchMovePosition;
    mTouchMovePosition = touch->getLocation();

    cocos2d::Vec2 delta = (mTouchMovePosition - mPreviousTouchPosition);
    delta = utility::Object::getContainingScene()->convertToNodeSpace(delta);
    mNewPosition = utility::Object::getPosition() + delta;

    utility::Object::setPositionTo(mNewPosition);
}

Notice I set the mTouchMovePosition to equal the area of the screen that has been touched.

bool Trooper::onTouchBegan(cocos2d::Touch * touch, cocos2d::Event * event)
{
    mTouchMovePosition = mTouchPosition = utility::Object::getContainingScene()->convertTouchToNodeSpace(touch);
    return true;
}

It works! I hoped it help somebody who is trying to achieve similar thing.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .