public Vector2 Intersection(Line2D line) { float tThis, tThat; IntersectTees(line, out tThis, out tThat); return Point1 + tThis * (Point2 - Point1); }
public Vector2 SegmentIntersection(Line2D line) { float tThis, tThat; IntersectTees(line, out tThis, out tThat); if (tThis < 0 || tThis > 1 || tThat < 0 || tThat > 1) return new Vector2(float.NaN, float.NaN); return Point1 + tThis * (Point2 - Point1); }
protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // Calculate new velocity and position Vector2 acceleration2D = Vector2.Zero; lock (accelerationLock) { acceleration2D = new Vector2(acceleration.X, -acceleration.Y); } float elapsedSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds; ballVelocity += GRAVITY * acceleration2D * elapsedSeconds; Vector2 oldPosition = ballPosition; ballPosition += ballVelocity * elapsedSeconds; bool needAnotherLoop = false; do { needAnotherLoop = false; foreach (Line2D line in borders) { Line2D shiftedLine = line.ShiftOut(BALL_RADIUS * line.Normal); Line2D ballTrajectory = new Line2D(oldPosition, ballPosition); Vector2 intersection = shiftedLine.SegmentIntersection(ballTrajectory); float angleDiff = MathHelper.WrapAngle(line.Angle - ballTrajectory.Angle); if (Line2D.IsValid(intersection) && angleDiff > 0 && Line2D.IsValid(Vector2.Normalize(ballVelocity))) { float beyond = (ballPosition - intersection).Length(); ballVelocity = BOUNCE * Vector2.Reflect(ballVelocity, line.Normal); ballPosition = intersection + beyond * Vector2.Normalize(ballVelocity); needAnotherLoop = true; break; } } } while (needAnotherLoop); base.Update(gameTime); }
void IntersectTees(Line2D line, out float tThis, out float tThat) { float den = line.Vector.Y * this.Vector.X - line.Vector.X * this.Vector.Y; tThis = (line.Vector.X * (this.Point1.Y - line.Point1.Y) - line.Vector.Y * (this.Point1.X - line.Point1.X)) / den; tThat = (this.Vector.X * (this.Point1.Y - line.Point1.Y) - this.Vector.Y * (this.Point1.X - line.Point1.X)) / den; }