How to create vectors and create collisions using kinetic js

121 views Asked by At

I am using kinetic js and would like to implement vector physics and collision theory using it.

like I am striking a ball with a draggable stick.

The stick could strike the ball at any angle and the ball should move according to the angle / direction.

In the fiddle here, there is a white ball. on clicking it the stick appears at the angle in which we clicked the ball.

The stick is draggable along that initial direction only. on mouse leave the stick drops to the initial position, touching the ball.

I want the ball to move according to the direction of the stick and implement collision theory using kinetic js.

Now the ball move to the top left corner of the window.

strikerGroup.on('dragend', function(){
          strikerGroup.setPosition(initStrikerGrpX, initStrikerGrpY);
          striker.speedX = striker.speedY = 2;

          var strikeranimtion = new Kinetic.Animation(function(frame) {
            striker.setX(striker.x - striker.speedX * (frame.timeDiff / jincr));
            striker.setY(striker.y + striker.speedY * (frame.timeDiff / jincr));
            jincr -= 0.0000025;
            if (striker.y < 0 || striker.x < 0) {
             console.log("********")
           }
         }, layer);
          strikeranimtion.start();

          layer.draw();
          // strikerGroup striked the striker!!!!
        });

Please help.

Thanks in advance.

1

There are 1 answers

2
markE On

Given a line and a circle defined like this:

var line={
    x0:50,
    y0:50,
    x1:100,
    y1:100
}

var ball={
    cx:75,
    cy:75,
    radius:15
}

You can determine if they are colliding like this:

function isBallLineColliding(line,ball) {

// calculate the point on the line that's closest to the ball

lerp=function(a,b,x){ return(a+x*(b-a)); };
var dx=line.x1-line.x0;
var dy=line.y1-line.y0;
var t=((ball.x-line.x0)*dx+(ball.y-line.y0)*dy)/(dx*dx+dy*dy);
var lineX=lerp(line.x0, line.x1, t);
var lineY=lerp(line.y0, line.y1, t);

// if the ball centerpoint is closer than 1 radius length
// to the line, then the ball is colliding with the line

var dx1=ball.x-lineX;
var dx2=ball.y-lineY;
return(dx1*dx1+dy1*dy1<ball.radius*ball.radius);

};

If you're using a rect instead of a line as your stick then add half the stick width to the test:

return(dx1*dx1+dy1*dy1<ball.radius*ball.radius+rect.width/2*rect.width/2);

And the rebound angle would be the difference between the line angle and the ball angle (ball angle is angle between current and previous ball position).