Predictive trajectory line of GameObject (SOLVED)

I’m trying to make the trajectory of ball before the use of force.

the example of the realisation in box2d, got from Phaser examples

    function getTrajectoryPoint(startX, startY, velocityX, velocityY, n) {
        //velocity and gravity are given per second but we want time step values here
        var t = 1 / 60.0; // seconds per time step (at 60fps)
        
        var stepVelocityX = t * game.physics.box2d.pxm( -velocityX ); // m/s
        var stepVelocityY = t * game.physics.box2d.pxm( -velocityY );
        
        var stepGravityX = t * t * game.physics.box2d.pxm( -game.physics.box2d.gravity.x ); // m/s/s
        var stepGravityY = t * t * game.physics.box2d.pxm( -game.physics.box2d.gravity.y );

        startX = game.physics.box2d.pxm(-startX);
        startY = game.physics.box2d.pxm(-startY);
        
        var tpx = startX + n * stepVelocityX + 0.5 * (n*n+n) * stepGravityX;
        var tpy = startY + n * stepVelocityY + 0.5 * (n*n+n) * stepGravityY;
        
        tpx = game.physics.box2d.mpx(-tpx);
        tpy = game.physics.box2d.mpx(-tpy);
        
        return { x: tpx, y: tpy };
    }

any idea and thoughts how to do it in Defold?

1 Like

found one more realisation of this way in ActionScript by Emanuele Feronato. but it also use box2d feature.

for now I see only one thing in Defold to do this: use own simple physics to calculate this, and no use apply_force for gameObjects.

If you know the mass of the object, the gravity and the force that you intend to apply then that should be all you need to calculate it on your own right?

EDIT: And friction

1 Like

Here you go:

Projectile Trajectory Demo.zip (58.2 KB)
Click and drag to change the trajectory, right-click to fire.

You can look up the formula for an ideal projectile’s trajectory:

-- Projectile position at a given time after launch
x = initial_pos.x + initial_velocity.x * time
y = initial_pos.y + initial_velocity.y * time - 1/2 * G * time * time

This doesn’t seem to match quite perfectly to Defold (it’s a little high at the apex), but it’s pretty darn close. You probably just have to tweak the gravity a tiny bit to match it up.

[Edit] Yeah, try multiplying G by 1.01, then it looks pretty good (at the end of line 4 of player.script in my demo)

6 Likes

That’s what I need! Thanks a lot! :cat:

yes, I see that no 100% match with Defold physics, but it’s enough in my case.

2 Likes

Hey @ross.grams . I found this demo instrumental but I noticed it may not have been on GitHub to inspire others, so I just setup a demo for it with the latest changes to make it work on the latest Defold Version:

May for sure help all of us.

4 Likes