简体   繁体   中英

Projectile velocity box2d

I want to launch projectiles from the bottom-right corner of the screen towards the left side of the screen. Now, I want the projectiles to fly with random velocities and angles according to the screen dimensions , just like that. Now, I know this is very simple but from some reason I can't manage to make this work.

Here is what I have tried so far:

My first try - Launch function

private void launchProjectile() {
        projectiles.peek().getBody().applyForce(projectiles.peek().getBody().getWorldVector(new Vector2(MathUtils.random(-20,-1*SCALAR_HEIGHT),
        MathUtils.random(2*SCALAR_HEIGHT,8*SCALAR_HEIGHT)).scl(MathUtils.random(3*SCALAR_HEIGHT,5*SCALAR_HEIGHT))), 
        projectiles.peek().getBody().getWorldCenter(), true);
        Gdx.app.log("System", String.valueOf(SCALAR_HEIGHT));
    }

Here is my second try - Launch function

private void launchProjectile() {
    float xVelocity;
    float yVelocity;
    xVelocity = (float) MathUtils.random(0,0)*SCALAR_WIDTH/2;
    yVelocity = (float) MathUtils.random(20,20)*SCALAR_HEIGHT;
    velocityProjectile.set(xVelocity,yVelocity); // Sets the velocity vector to the above values
    velocityProjectile.sub(projectiles.peek().getBody().getPosition());
    velocityProjectile.nor(); // Normalize the vector - Now it's fine and ready!
    // Sets the start velocity of the projectile Trajectory to the current velocity
    projectiles.peek().getBody().setLinearVelocity(velocityProjectile.scl(18+SCALAR_HEIGHT));
}

In both tries, the projectile flies way more than I need and it doens't take in consideration the screen size like it should.

Can you guys please tell me what is the right way to do this?

Thanks!!

Start with this page: http://www.iforce2d.net/b2dtut/projected-trajectory

In the "How fast should it be launched to reach a desired height?" section, you can see how much vertical velocity will be required to make the projectile reach the top of the screen. So you would pick a random number less than that, to make sure it doesn't go off the top of the screen.

Next, in the "How high will it go?" section, you can see the formula to find out how many time steps it will take for the projectile to reach maximum height. It will then take the same amount of time to come back down to the starting height. For example, let's say it would take 60 time steps to reach maximum height. That means it would take 120 time steps to fall down again to the same height as it started. Then you can set the horizontal part of the launch velocity so that it cannot go outside the screen in 120 time steps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM