Вопрос

I'm currently developing a 2-player Ping-Pong game (in 2D - real simple) from scratch, and it's going good. However Theres a problem I just can't seem to solve - I'm not sure if this should be located here or on MathExchange - anyway here goes.

Initially the ball should be located in the center of the canvas. When pressing a button the ball should be fired off in a completely random direction - but always with the same velocity.

The Ball object has (simplified) 4 fields - The position in X and Y, and the velocity in X and Y. This makes it simple to bounce the ball off the walls when it hits, simple by inverting the velocities.

    public void Move()
    {
        if (X - Radius < 0 || X + Radius > GameWidth)
        {
            XVelocity = -XVelocity;
        }
        if (Y - Radius < 0 || Y + Radius > GameHeight)
        {
            YVelocity = -YVelocity;
        }
        X+= XVelocity;
        Y+= YVelocity;
    }

I figured the velocity should be the same in each game, so I figures I would use Pythagoras - the square of the two velocities should always be the same.

SO for the question:

Is there a way to randomly select two numbers (doubles) such that the sum of their squares is always a specific number - more formally:

double x = RandomDouble();
double y = RandomDouble();
if (x^2 + y^2 = 16) {/* should always be true */ }

Any help appreciated :)

Это было полезно?

Решение

Randomly pick an angle theta and multiply that by the magnitude of the distance d you want. Something like:

double theta = rand.NextDouble() * 2.0 * Math.PI;
double x = d * Math.Cos(theta);
double y = d * Math.Sin(theta);

Другие советы

If the constant is C, pick a number x between 0 and sqrt(C).

Solve for the other number y using simple algebra.

why not try this:

double x = RandomDouble();
double y = square(16-x^2);

as your application allow double type.
does this solve your problem?
if not, please let me know

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top