S
S
Sergey2015-11-29 16:01:36
C++ / C#
Sergey, 2015-11-29 16:01:36

How to convert mouse coordinates to tile coordinates?

The location of the tile on the screen is calculated according to the following formula:

inline sf::Vector2f  tile2screen_pos(uint32_t  x, uint32_t  y) {
    return sf::Vector2f((m_tile_size / 2 * static_cast<float>(x)) + (m_tile_size / 2 * static_cast<float>(y)),
                        (m_tile_size / 4 * static_cast<float>(y)) - (m_tile_size / 4 * static_cast<float>(x)));
  }

Note: The tile size ( m_tile_size) is 40px. Of these, in height, the tile itself occupies the bottom 20px. Therefore, dividing by 4.
Tried to count as follows:
inline sf::Vector2u  screen2tile_pos(int32_t  x, int32_t  y) {
    return sf::Vector2u(
      (x / m_tile_size / 2 + y / m_tile_size / 2),
      (x / m_tile_size / 4 + y / m_tile_size / 4)
    );
  }

However, the tile is selected far from the top-left.
PS call code screen2tile_pos:
m_selection = this->screen2tile_pos(event.mouseButton.x + m_camera.getViewport().left, event.mouseButton.y + m_camera.getViewport().top);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-01-01
@DrMGC

Using the system of equations, it was possible to deduce the following:

int  xs, ys; // Координаты на экране
unsigned int  xt, yt; // Координаты Тайлов
const int  T; // Размер тайла

If a
xs = (T / 2 * static_cast<float>(xt)) + (T / 2 * static_cast<float>(yt));
ys = (T / 4 * static_cast<float>(yt)) - (T / 4 * static_cast<float>(xt));

Then:
xt = (xs - ys) / T;
yt = (xs + ys) / T;

O
Oleg Tsilyurik, 2015-11-29
@Olej

It 's not clear what the question is about ... but:
m_tile_size / 2 * static_cast(x) and x / m_tile_size / 2 are completely different things.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question