I am attempting to make a Particle start moving to the position of my finger on the touch of the screen.

I have been using this as the basis so far:

public void update()
    deltaX *= .9;
    deltaY *= .9;

    this.x += this.deltaX;
    this.y += this.deltaY;

public void moveTo(int newX, int newY)
    float dx = newX-this.x;
    float dy = newY-this.y;

    float length = (float) Math.sqrt(dx*dx+dy*dy);


    dx *= 10;
    dy *= 10;

    deltaX = dx;
    deltaY= dy;

now while it does move the Particle, it is rarely in the direction of my finger. How can I make the particle have the correct amount of velocity to get to the position of my finger, but no farther?

Thanks in advance!

  • \$\begingroup\$ I have found plenty of resources but I still cannot seem to make it move in the correct direction. It's almost like it's moving in the opposite direction, but not quite.. \$\endgroup\$ Aug 26 '14 at 0:58

To make a particle track your finger motion you first need to track at least two different events in onTouchEvent(), and possibly a third depending on what you want to happen when you lift your finger. You need to check for MotionEvent.ACTION_DOWN and MotionEvent.ACTION_MOVE, and possibly MotionEvent.ACTION_UP. The first event you will set the initial target location, and the second event will tell you where to alter the target location to. If you want to particle to travel to the last location of your finger after you lift it you can just ignore MotionEvent.ACTION_UP.

public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN ||event.getAction() == MotionEvent.ACTION_MOVE) {
        particle.moveTo(event.getX(), event.getY());
    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        // add code here if particle behavior changes on finger lift

This should make sure the particle has the correct trajectory. Whether or not it has the correct velocity is harder to say without knowing more about how you are controlling the timing of the animation. If you have a fixed time delta then the code you have should be fine. If your delta time between animations frames if variable then you should be factoring this into your update function.

Also, you can calculate the rotation angle of the particle in the moveTo() code if needed.

pubic void moveTo(int newX, int newY) {
    float diffX = newX - this.x;
    float diffY = newY - this.y;
    float length = (float) Math.sqrt(diffX*diffX+diffY*diffY);
    float normalizedX = diffX/length;
    float normalizedY = diffY/lenght;

    float angle = (float)Math.acos(normalizedX);
    if (diffY > 0.0f) {
        rotation = (float)Math.toDegrees(angle);
    } else {
        rotation = (float)Math.toDegrees(-angle);

    deltaX = normalizeX * 10;
    deltaY = normalizedY * 10;

You must log in to answer this question.

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