Line rectangle collision? | SoloLearn: Learn to code for FREE!

+2

Line rectangle collision?

How do I do line rectangle collision? It seems way more complex than usual, here's the code. I'm trying to make r1 collide with the blue lines on r2. The collision method is vertextIntersect() in the Rect object. I am not asking for rect collision, I am asking for line rect collision. The code draws blue lines over the second rectangle, I want to collide with 1 line. https://code.sololearn.com/W7N67EeZEjkC/?ref=app

8/2/2020 8:33:18 AM

Clueless Coder

29 Answers

New Answer

+3

https://code.sololearn.com/WGBLLnFkuMpR/?ref=app

+6

P5js has an additional collision module with examples. https://github.com/bmoren/p5.collide2D

+5

ok... a m*n rectangle has m*n points. a k*1 line has k points. if any point of k is in rectangles point... collision.

+5

now optimize atm your lines horizontal and vertical lines?

+5

width*height and length of objects

+5

Rectangle Collision Testing https://code.sololearn.com/WOSkh92TwAYI/?ref=app Circle

+5

https://bit.ly/2XkTBnt Clueless Coder again the little sketch.

+4

👍thanks a million

+3

Clueless Coder Quite close Center of moving square, correct. For blue line, make it not a vertical line, make it with a random angle. Find the nearest point on the line which has shortest distance from center of square. Calculate the distance between that point and the center of square.

+2

Oma Falk I know, but I want to learn the theory

+2

This might help you. http://jeffreythompson.org/collision-detection/rect-rect.php

+2

Oma Falk Just remembered, collide2d won't work with my rectangle configuration. It only works with rectMode(CORNER)

+2

Calculate the normal length from line to center of shape , and then compare with the length of shape at that direction.

+2

Gordon Thanks, that very nearly worked. It's bit off though, I may have misunderstood. This is way to advanced for me I think. I added it to the code

+2

For solving rect1 being stuck to rect2 currently, here is my demo for another Sololearner a year ago : https://code.sololearn.com/W385n4ccicXX/?ref=app Use a flag to indicate that the shaped are overlapping, so that the direction will not be switching every frame.

+2

If it is vertical, you just need to check right side of rect1 with rect2.x

+2

Gordon I tried something else and it's got worse. This is impossible.

+2

I'll explain in a YouTube video, if you need.

+2

Thanks so much! I actually get it now!

+2

👍