rotate sprite and shooting bullets from the end of a cannon

Posted by Alberto on Game Development See other posts from Game Development or by Alberto
Published on 2012-10-06T17:27:41Z Indexed on 2012/10/06 21:56 UTC
Read the original article Hit count: 292

Filed under:
|
|
|
|

Hi all i have a problem in my Andengine code,

I need , when I touch the screen, shoot a bullet from the cannon (in the same direction of the cannon) The cannon rotates perfectly but when I touch the screen the bullet is not created at the end of the turret

This is my code:

private void shootProjectile(final float pX, final float pY){
    int offX = (int) (pX-canon.getSceneCenterCoordinates()[0]);
    int offY = (int) (pY-canon.getSceneCenterCoordinates()[1]);
    if (offX <= 0)
            return ;
    if(offY>=0)
                    return;

    double X=canon.getX()+canon.getWidth()*0,5;
    double Y=canon.getY()+canon.getHeight()*0,5 ;
    final Sprite projectile;
    projectile = new Sprite( (float) X, (float) Y,
                    mProjectileTextureRegion,this.getVertexBufferObjectManager() );

    mMainScene.attachChild(projectile);


    int realX = (int) (mCamera.getWidth()+ projectile.getWidth()/2.0f);
    float ratio = (float) offY / (float) offX;
    int realY = (int) ((realX*ratio) + projectile.getY());

    int offRealX = (int) (realX- projectile.getX());
    int offRealY = (int) (realY- projectile.getY());
    float length = (float) Math.sqrt((offRealX*offRealX)+(offRealY*offRealY));
    float velocity = (float) 480.0f/1.0f;
    float realMoveDuration = length/velocity;

    MoveModifier modifier = new MoveModifier(realMoveDuration,projectile.getX(), realX, projectile.getY(), realY);
    projectile.registerEntityModifier(modifier);
}

@Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {

    if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_MOVE){

        double  dx = pSceneTouchEvent.getX() -  canon.getSceneCenterCoordinates()[0];
        double  dy = pSceneTouchEvent.getY() -  canon.getSceneCenterCoordinates()[1];

        double  Radius = Math.atan2(dy,dx);
        double Angle = Radius * 180 / Math.PI;
        canon.setRotation((float)Angle);

        return  true;

    }
    else if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){

        final float touchX = pSceneTouchEvent.getX();
        final float touchY = pSceneTouchEvent.getY();

        double  dx = pSceneTouchEvent.getX() -  canon.getSceneCenterCoordinates()[0];
        double  dy = pSceneTouchEvent.getY() -  canon.getSceneCenterCoordinates()[1];

        double  Radius = Math.atan2(dy,dx);
        double Angle = Radius * 180 / Math.PI;

        canon.setRotation((float)Angle);
        shootProjectile(touchX, touchY);
    }

    return false;
}

Anyone know how to calculate the coordinates (X,Y) of the end of the barrel to draw the bullet?

© Game Development or respective owner

Related posts about java

Related posts about android