0
\$\begingroup\$

I am trying to make a sling-shot that fires a projectile. I want it to act like the standard sling-shot in angry birds.

So far I managed to get the "pulling" effect, ie. If I draw backwards it fires in the opposite angle of the direction my finger went, and with different speeds depending on how far I dragged the finger from the "start-position".

Touch Code/logic:

@Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        touchPos.set(screenX, screenY, 0);
        camera.unproject(touchPos);
        Vector2 temp = new Vector2(touchPos.x, touchPos.y);

        Vector2 d = temp.sub(startPos); //subtract finger-position from start-position
        float velX = d.x * FIRE_SPEED; //add speed
        float velY = d.y * FIRE_SPEED;
        d.set(velX, velY); // set the velocity

        projectile.setVelocity(d); //send velocity to object
        projectile.setFired(true); //signal the object that its been fired

        return false;
    }

Object Code:

public void update(float delta){
        if(fired){
            pos.x -=  velocity.x * delta; //since I want it to move the opposite direction of where I dragged, I subtract
            pos.y -=  velocity.y * delta;
        }
    }

How would I go about adding gravity here? I want it to shoot in the set direction, then after a certain time/distance I want it to start falling (taking into account the direction so that it looks like real gravity), exactly as in angry birds.

\$\endgroup\$
1
\$\begingroup\$

You add the gravitational acceleration to the vertical component of velocity.

    if(fired){
        pos.x -=  velocity.x * delta; //since I want it to move the opposite direction of where I dragged, I subtract
        pos.y -=  velocity.y * delta; 
        velocity.y += g*delta;
    }
\$\endgroup\$
1
\$\begingroup\$

Gravity is a constant downward acceleration. Acceleration is a change in velocity.

Simply subtract a constant value from velocity.y every update.

public void update(float delta){
    if(fired){
        velocity.y -= GRAVITY * delta;
        pos.x -=  velocity.x * delta; 
        pos.y -=  velocity.y * delta;
    }
}

The ideal value for GRAVITY depends on the scale of your game and is something you need to find out through experimentation.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .