Search code examples
javalibgdx

Actor shakes when it is near the destination Vector2


The issue is when the Actor/Entity moves towards the click position, as its about 1 tile away the character starts shaking as in it moves up 7 pixels, then moves down 7 pixels over and over not reaching the destination.

I've tried a few different methods but all seem to end in the same way, it might be possible it only needs to go up a few pixels but since the speed is 7 it moves too far, then moves back.

if (Objects.nonNull(next)) {
            if (this.getDistanceVector(next) <= 64) {
                return;
            }

            double destX = next.y*64 - this.getX();
            double destY = next.x*64 - this.getY();

            double dist = Math.sqrt(destX * destX + destY * destY);
            destX = destX / dist;
            destY = destY / dist;

            double travelX = (destX * speed);
            double travelY = (destY * speed);

            this.moveBy((float) travelX, (float)travelY);
        } else {
            moveTo = null;
        }

It should walk to the position and stop, it currently walks close then shakes on the x axis or the y axis depending on location of click.


Solution

  • By checking the speed is greater then distance, i was able to make a smooth transition without any jitter.

    if (speed > dist) {
                    destX = target.y - this.getX();
                    destY = target.x - this.getY();
    
                    destX = destX / dist;
                    destY = destY / dist;
    
                    double travelX = (destX * speed);
                    double travelY = (destY * speed);
    
                    this.setX((int)travelX);
                    this.setY((int)travelY);
                } else {
                    destX = destX / dist;
                    destY = destY / dist;
    
                    double travelX = (destX * speed);
                    double travelY = (destY * speed);
    
                    this.moveBy((float) travelX, (float)travelY);
                }