Search code examples
androidandengine

Andengine - Shooting bullets in front of rotating gun


Hello I searched in the forum,but coudn't find a helpful answer. I'm making a game with AndEngine and I'm stuck for 3 days on shooting from rotating sprite.

That is my code and how I rotate the gun.I tried here to shoot a bullet ,but it shoots from a wrong starting point I would want to shoot a bullet from the end of the gun.

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

    if(pSceneTouchEvent.isActionMove()){
          final float dX = pSceneTouchEvent.getX() - machine.getX();
          final float dY = pSceneTouchEvent.getY() - machine.getY();

        float angle = (float) Math.atan2(dX,dY);

        float rotation = MathUtils.radToDeg(angle) + 1;

        machine.setRotation(rotation - 90);

        Log.d("BUG",machine.getRotation() + "");
        if(machine.getRotation() >= 84  ){
            machine.setRotation(84);

        }
        if(machine.getRotation() <= -54 ){
            machine.setRotation(-54);


        }

        final int incrementXValue = 15;
        long sElapsed = System.currentTimeMillis() - lastFire;

        if(bulletsAmout > 0 && sElapsed > cooldownBetweenShoot * cdModd){

             e = new Entity(0,machine.getY());
             e.setRotation(getRotation());

             SceneManager.getInstance().getCurrentScene().attachChild(e);


                float x2 =  (float) (machine.getSceneCenterCoordinates()[0] + machine.getWidth() /2 * Math.cos(machine.getRotation()));
                float y2 = (float) (machine.getSceneCenterCoordinates()[1]  + machine.getWidth() /2 * Math.sin(machine.getRotation()));

                float realX = (float) (Math.toRadians(x2) + machine.getWidth());
                 realY = (float) Math.toRadians(y2);


            bullets = new Sprite(realX,realY, resourcesManager.bulletRegion.deepCopy(), vbom){
                protected void onManagedUpdate(float pSecondsElapsed) {
                    float currentX = this.getX();
                    this.setX(currentX + incrementXValue);
                    super.onManagedUpdate(pSecondsElapsed);

                }
            };
            bullets.setScale(0.06f);


            e.attachChild(bullets);
            projectilesToBeAdded.add(bullets);
            bulletsAmout--;
            lastFire = System.currentTimeMillis();
            setBulletsText(bulletsAmout);
            resourcesManager.pistolSound.play();


        }

        return true;
    }


    return false;

}

Solution

  • So I found how to fix that.

    The problem is in this line of code :

        e = new Entity(0,machine.getY());
    

    Should be :

         e = new Entity(machine.getX() - (machine.getHeight() / 2),machine.getY())