Efficient way of detecting a touched object in a game?
- by Pin
Imagine a Sims-like 2D game for a touch based mobile phone where one can interact with virtually any object in the scene.
How can I efficiently detect which object is being touched by the player?
In my short experience, looping through all the visible objects in the scene and checking if they're touched has so far done the job, but when there may be many many moving objects in the screen that sounds kind of inefficient isn't it? Keeping the visible moving objects list can consume time in itself as one may have to loop through all of them each frame.
Other solutions I've thought are:
Spatial hashing. Divide the screen as a grid and place the visible objects in the corresponding bucket. Detection of the clicked object is fast but there's additional overhead for placing the objects in the correct bucket each frame.
Maintaining a quad-tree. Moving objects have to be rearranged all the time, the previous solution looks better.
What is usually done in this case?