top of page
Search
cedarcantab

Studying Box2D-Lite in Javascript, Part 9.1: Raycast against Segment

Updated: Feb 28



	// p = p1 + t  d
    // v = v1 + s  e
    // p1 + t  d = v1 + s  e
    // s  e - t  d = p1 - v1
	rayCast(output, input, transform, childIndex) {
        // Put the ray into the edge's frame of reference.
        let p1 = b2MulT(xf.q, Vec2.Subtract(input.p1, xf.p));
        let p2 = b2MulT(xf.q, Vec2.Subtract(input.p2, xf.p));
        let d = Vec2.Subtract(p2, p1);

        let v1 = m_vertex1;
        let v2 = m_vertex2;
        let e = Vec2.Subtract(v2, v1);

        // Normal points to the right, looking from v1 at v2
        let normal = new Vec2(e.y, -e.x);
        normal.normalize();

        // q = p1 + t  d
        // dot(normal, q - v1) = 0
        // dot(normal, p1 - v1) + t  dot(normal, d) = 0
        let numerator = b2Dot(normal, v1 - p1);
        if (this.m_oneSided && numerator > 0.0)        {
            return false;
        }

        let denominator = b2Dot(normal, d);

        if (denominator == 0.0) {
            return false;
        }

        let t = numerator / denominator;
        if (t < 0.0 || input.maxFraction < t) {
            return false;
        }

        let q = Vec2.Add(p1, Vec2.Scale(t , d)) ;

        // q = v1 + s * r
        // s = dot(q - v1, r) / dot(r, r)
        let r = Vec2.Subtract(v2, v1);
        let rr = b2Dot(r, r);
        if (rr == 0.0)        {
            return false;
        }

        let s = b2Dot(Vec2.Subtract(q, v1), r) / rr;
        if (s < 0.0 || 1.0 < s)       {
            return false;
        }

        output.fraction = t;
        if (numerator > 0.0) {
            output.normal = -b2Mul(xf.q, normal);
        }
        else
        {
            output.normal = b2Mul(xf.q, normal);
        }
        return true;
    };

3 views0 comments

Recent Posts

See All

p2 naive broadphase

var Broadphase = require('../collision/Broadphase'); module.exports = NaiveBroadphase; /** * Naive broadphase implementation. Does N^2...

sopiro motor constranit

import { Matrix2, Vector2 } from "./math.js"; import { RigidBody } from "./rigidbody.js"; import { Settings } from "./settings.js";...

Comments


記事: Blog2_Post
bottom of page