Skip to content

Instantly share code, notes, and snippets.

@galek
Forked from Novum/gist:1108236
Created May 7, 2016 22:08
Show Gist options
  • Select an option

  • Save galek/6a27dafeec0c09188852686bcdb97930 to your computer and use it in GitHub Desktop.

Select an option

Save galek/6a27dafeec0c09188852686bcdb97930 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