Mouse input, finding tile below mouse.

I seem to be having a bit of trouble detecting the tile below my mouse cursor.

I have a 2d map that is 32x64 tiles in size, each tile is 32x32 pixels big. I move through the map using the arrow keys that += and -= xScroll & yScroll variables by a given speed.

I’m able to get the tile below the mouse by dividing the mouse x & y by 32. This all works fine until I start moving. The wrong tiles get selected when the xScroll & yScroll change. I’ve tried adding the xScroll & yScroll to the mouse x & y but that has no effect.

Here’s some source code. http://pastebin.com/XTqV2FdL

Just a hunch, but shouldn’t:


tileX = mouse.getX() + xScroll/ 32;
tileY = mouse.getY() + yScroll / 32;

be changed to:


tileX = (mouse.getX() + xScroll)/32;
tileY = (mouse.getY() + yScroll)/32;

The way it’s written, it divides the x/yScroll variable by 32 before adding it to the mouse X/Y position (order of operations still apply in Java). Be careful when relying on implicit behavior. It’s better to be as explicit as possible both for the benefit of the compiler and the maintainer. :slight_smile:

Just gave that a go but the tile selected still seems to be off.

Ky-6kHnMCPo

I’ve record the problem, hopefully this explains what’s going on better than I can.

Minus xScroll and yScroll not plus?

Cheers,

Kev

Minusing made the indicator stick to the tiles when the x/y scroll moved but still had the mouse x/y movement.

try performing some division , this is an issue I had and it seemed that one of the variables was twice what it should be for that function. it does seems to look like its * 2 so do



tileX = ((mouse.getX() + xScroll)/32)/2;
tileY = ((mouse.getY() + yScroll)/32)/2;

That doesn’t seem to work either, I tried dividing by different values in different places but no luck. :-\

Not having looked at your source code since I’m currently in a lecture, have you tried minusing and dividing?


if(key.right) xScroll += speed;

This means the more you scroll, [icode]xScroll[/icode] will be positive. So you need to subtract the scrolls to find a tile. This is how your fixed code looks like.


tileX = (mouse.getX() - xScroll)/32;
tileY = (mouse.getY() - yScroll)/32;

And that should hopefully fix the problem.