Moving sprites based on grid and touch

Moving sprites based on grid and touch
0.0 0



I’m using Tiled to generate a TMX map for grid positioning and Targeted Touch Delegate for touch.

What I’m trying to do is to move a sprite on the screen based on a grid and the sprite will snap to the grid based on where I touch. Problem is, the sprite isn’t exactly moving where I touch and it has something to do with the fact that I’m dealing with an isometric map.

Here is an image of what I’m talking about.

The blue lines represent mouse (touch) movements.
The black lines represent the sprite movements.

The lines across each arrow represent what direction for mouse corresponds to what direction of sprite.

For example, by dragging the sprite up (blue arrow with red line), the sprite will move “isometrically up” (black arrow with red line).

Here is the code:

void Touch::ccTouchMoved(CCTouch* touch, CCEvent* event)
    CCPoint touchLocation = touch->getLocation();
    CCPoint oldTouchLocation = touch->getPreviousLocation();

    CCPoint translation  = ccpSub(touchLocation, oldTouchLocation);
    CCPoint diff = ccpSub(touchLocation, defaultPos);

    this->panForTranslation(translation, diff);

void Touch::panForTranslation(CCPoint translation, CCPoint diff)
    if(pSelSprite) //Moves specific sprite
        diff.x = floor(diff.x / tileWidth);
        diff.y = floor(diff.y / tileHeight);

        CCPoint snapPos = pTileLayer->positionAt(ccp(diff.x, -diff.y));

    else //Moves background
        CCPoint newPos = ccpAdd(this->getPosition(), translation);

void Touch::convertIsoToScreen(CCPoint &spriteCoordinates)
    //Calculations for converting tile coordinates to screen coordinates
    //1. Obtain Tile Width and Height and their Half. Normally (32, 64) or ([2^X], 2[2^X])
    tileWidth = pTileLayer->getMapTileSize().width;
    tileHeight = pTileLayer->getMapTileSize().height;
    halfTileWidth = tileWidth / 2.0f;
    halfTileHeight = tileHeight / 2.0f;

    //2. Obtain Origin Coordinates of Tile Map
    float mapOriginX = pTileMap->getPosition().x;
    float mapOriginY = pTileMap->getPosition().y;

    //3. Add the Origin Offset to Object Coordinates
    mapOriginX = mapOriginX + spriteCoordinates.x;
    mapOriginY = mapOriginY + spriteCoordinates.y;

    spriteCoordinates.x = mapOriginX;
    spriteCoordinates.y = mapOriginY;

I realise that the solution is probably simple but my logic is horrible. So, what should I change in my code to make the touch and grid sync? Is there a better way to move the sprite that snaps to the grid? Thanks.

Example.png (53.5 KB)



Did you solved your problem ?
I trying to do the same thing