Skip to content

Instantly share code, notes, and snippets.

@Novum
Created July 26, 2011 22:25
Show Gist options
  • Save Novum/1108236 to your computer and use it in GitHub Desktop.
Save Novum/1108236 to your computer and use it in GitHub Desktop.
// Tests each segment for a hit. All calculations are done in screen space pixel coordinates
bool CollisionPath::hitTest(const ViewportPosition &selection_position) const
{
const Vector2 &mouse_pixel_pos = selection_position.getPixelPosition();
const Viewport &viewport = selection_position.getViewport();
const Camera &camera = viewport.getCamera();
const WorldLayer &layer = *getLayer();
for(auto iter = anchors.begin(); iter != anchors.end()-1; ++iter) {
const Vector2 &segment_begin =
camera.projectToPixels(viewport, *iter, layer.getDistance());
const Vector2 &segment_end =
camera.projectToPixels(viewport, *(iter+1), layer.getDistance());
// Calculate nearest position on segment from mouse
const Vector2 begin_to_end_v = (segment_end - segment_begin);
const float segment_length = begin_to_end_v.length();
const Vector2 segment_normal = begin_to_end_v / segment_length;
const float t = segment_normal * (mouse_pixel_pos - segment_begin);
const Vector2 nearest_pos = segment_begin + (segment_normal * t);
// Check if point lies outside of segment
if(t < 0.0f || t > segment_length) {
continue;
}
// Calculate layer distance from mouse position
const Vector2 mouse_to_nearest_pos_v = nearest_pos - mouse_pixel_pos;
const float mouse_to_segment_distance = mouse_to_nearest_pos_v.length();
if(mouse_to_segment_distance < 3.0f) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment