How to move an object in a certain direction

2

Hi, I want to create the effect of throwing an object, in this case a circle that is drawn in the canvas . The problem is that I do not understand how to identify where to touch on the screen and move the circle in that direction. My final idea would be something like that image.

Any help is useful. Thanks

This is the code I have so far:

    public class Juego extends SurfaceView implements View.OnTouchListener{

    Paint paint;
    int x, y, radio = 100, velocidadX = 5, velocidadY = 5, tocoY, tocoX;
    boolean mover = false;
    boolean una_vez = true;

    public Juego(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setOnTouchListener(this);
        setFocusable(true);

        paint = new Paint();
    }


    public void onDraw(Canvas canvas){
        paint.setColor(Color.WHITE);
        canvas.drawRect(0,0,canvas.getWidth(),canvas.getHeight(),paint);

        if (una_vez == true){
            x = canvas.getWidth()/2;
            y = canvas.getHeight()/2;
            una_vez = false;
        }

        paint.setColor(Color.BLACK);
        canvas.drawCircle(x, y, radio, paint);

        if (mover == true){

                if (x >= canvas.getWidth() - radio) {
                    velocidadX = -5;
                }

                if (x <= radio) {
                    velocidadX = 5;
                }

                if (y >= canvas.getHeight() - radio) {
                    velocidadY = -5;
                }

                if (y <= radio) {
                    velocidadY = 5;
                }

            x = x + velocidadX;
            y = y + velocidadY;
        }

        invalidate();
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case (MotionEvent.ACTION_DOWN):

                tocoX = (int) motionEvent.getX();
                tocoY = (int) motionEvent.getY();

                mover = true;

                return true;
            default:
                return super.onTouchEvent(motionEvent);
        }
    }
}
    
asked by Agustin Val 13.02.2018 в 17:43
source

0 answers