Jump to content

Detect collision by drawing line


Lyian
 Share

Recommended Posts

Hi Community!

 

I try to draw a line which follows the angle of my cursor. It shouldn't stop at my cursor but rather follow its direction until a collision happens. 

As for now I am able to draw the line on every update which follows perfectly my cursor, but stops then. 
I had the idea to "fire" a sensor (trigger) along the line to check when a collision happens. 

My goal is to archieve this effect with p2js.

 

 
create(){game.input.addMoveCallback(move, this);}    function draw(){       bmd.clear();    bmd.ctx.beginPath();    bmd.ctx.beginPath();    bmd.ctx.moveTo(ship.x, ship.y);    bmd.ctx.lineTo(game.input.x , game.input.y);    bmd.ctx.lineWidth = 4;    bmd.ctx.stroke();    bmd.ctx.closePath();    bmd.render();   }function move(pointer, x, y, isDown) {    mouseBody.body.x= x;    mouseBody.body.y= y;  }function update() {        draw();    }

post-16309-0-04468300-1441645775.png

Link to comment
Share on other sites

Actually I have a line which is drawn between cursor and a ball which is fired by clicking. So the length is in this case determined by the cursor on the screen but should be determined by collision, like in the picture above. 
My idea was to use sensors and fire them along the line until a collision happens, but firstly I dont't know how to do this exactly and I am afraid that the collision won't work at the speed which is required to let the line appear instantly. 

 

Link to comment
Share on other sites

Y'know, since you're making a pool game you probably don't need to rely on the physics simulation to draw this line for you. You're guaranteed to have an upper limit on the number of bodies you care about (20 at most) and calculating an intersection of a line and a circle is pretty cheap. So maybe just iterate through every ball in your world and check to see if/where it intersects the line then draw the result in real time. That way you don't have to worry about tunneling, etc.

 

This article looks promising: http://math.stackexchange.com/questions/228841/how-do-i-calculate-the-intersections-of-a-straight-line-and-a-circle

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...