self.hitBall = function (ball, x, y){

        var angle = Math.atan2((x - ball.centerX), (y - ball.centerY));
        ball.velocityY = (Math.sin(angle) * 10);
        ball.velocityX = (Math.cos(angle) * 10);


So the function takes in the ball, which has a centerX variable and a centerY variabe. The x and y passed into the function is the x and y is the point the ball was hit. I want to make the ball travel in the direction it was hit from.

Not really sure why my code isn't working.. it's behaving very strangely and I'm not that good with trig so I'm not really quite sure why it isnt working.

  • 2
    \$\begingroup\$ Beware that usually atan2 takes y as first argument! \$\endgroup\$ – Margaret Bloom Apr 3 '16 at 19:13

Assuming that you mean the x,y passed in is the point on the ball that you hit. A bit like the cue position when you hit a ball with a snooker cue. You can do it with a bit of vector maths.

    // create direction vector for ball to go. 
    var dirX = ball.centerX - x;
    var dirY = ball.centerY - y;

    // convert dir to unit vector. this'll make it easier to create a set magnitude later
    var magnitude = Sqrt( (dirX * dirX) + (dirY * dirY) );
    dirX /= magnitude;
    dirY /= magnitude;

    ball.velocityX = dirX * 10;
    ball.velocityY = dirY * 10; 
| improve this answer | |

Physical 4 State Linear Translation----------

FORCE- The amount of force the ball was hit.(kg)

ACCELERATION- That same force divided by the mass of the ball


VELOCITY- Acceleration over time is Velocity



Velocity over time changes the position


DIRECTION Position is determined by direction on both axis

X=(Force/Mass)*T^2 *sin(Direction)
Y=(Force/Mass)*T^2 *cos(Direction)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.