1
\$\begingroup\$

Starting to gamedev again and Trying an isometric game. However, all I try, I can't seem to figure out tile picking properly.. Using SFML

Here's how I'm detecting the clicks and moving around a sf::View. Sprites are 64*32

#include "GameWorld.h"
#include <math.h>
GameWorld::GameWorld()
{
    this->camX = 0;
    this->camY = 0;
    this->factories.push_back(new Factory("Factory 1"));
}

void GameWorld::draw(sf::RenderWindow * win, ContentManager* contentManager) {
this->factories.at(this->activeFactory)->render(win,contentManager, this->camX, this->camY);
}

void GameWorld::update(float delta, sf::RenderWindow* win) {
    float speed= 128;
    sf::View view = win->getView();

if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
    this->camY -= speed*delta;

}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
    this->camX -= speed*delta;

}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
    this->camY += speed*delta;

}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
    this->camX += speed*delta;
}
view.setCenter(this->camX,this->camY);

win->setView(view);

if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {

sf::Vector2i selectedTile;
int x = sf::Mouse::getPosition(*win).x - this->camX;
int y = sf::Mouse::getPosition(*win).y - this->camY;
selectedTile.x = (y + x/2)/32;
selectedTile.y = (y - x/2)/32;

        printf("%d %d %d %d\n",sf::Mouse::getPosition(*win).x,sf::Mouse::getPosition(*win).y, selectedTile.x,selectedTile.y);
   }


}

The map is a 2d vector, which gets drawn like so

float screenX = (indexX - indexY) * this->sprite->getGlobalBounds().width/2;
float screenY = (indexX + indexY) * this->sprite->getGlobalBounds().height/2;


this->sprite->setPosition(sf::Vector2f(screenX,screenY));

win->draw(*this->sprite);

Here's what this currently prints out: When the game is loaded initially - clicking the first tile rendered (0,0) outputs 21 0 as the computed coords. As you can see, the X value is completely off, and the Y value goes off aswell as soon as I move the view in any direction. How could I get this picker to work properly?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Problem solved.

Working code thanks to https://www.twitch.tv/siegegames

    sf::Vector2f view_mouse_position = win->mapPixelToCoords(sf::Mouse::getPosition(*win));
    float x = view_mouse_position.x / 64;
    float y = view_mouse_position.y / 32;

    int tile_x = x + y;
    int tile_y = x - y;
\$\endgroup\$

You must log in to answer this question.

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