DarkLeafyGreen
DarkLeafyGreen

Reputation: 70416

Create impulse vector from touch location

imagine I have a ball. The user touches it and the ball goes up. For now the impulse direction is static

ball->ApplyLinearImpulse(b2Vec2(20.0f,100.0f),ball->GetWorldCenter());

and

b2Vec2(20.0f,100.0f)

is the impulse vector. I want to have a impulse vector generated randomlly. I think this should be done by optaining the touch location on the ball.

This question is more about mathematics. How can I calculate a random impulse vector according to the touch location? Any ideas?

Upvotes: 0

Views: 214

Answers (1)

Dan F
Dan F

Reputation: 17732

Simple solution would be to create a vector from the ball's location to the touch location, and use a scaled version of that as your impulse vector.

Edit: Some pseudo-code to calculate this vector

-(void) createImpulse(Vector touchPoint)
{
    //this is now a vector pointing from the touch point to the ball
    Vector diff = [ball->GetWorldCenter() vectorSubtract:touchPoint];
    //Generate a random float from 1/2 to 2
    float scale = randFloat(0.5f, 2.0f);
    //Scale the vector by the float
    Vector impulse = [diff scaleBy:scale];
    ball->ApplyLinearImpulse(b2Vec2(impulse.x, impulse.y), ball->GetWorldCenter() );
}

Upvotes: 1

Related Questions