jeudi 21 décembre 2017

Random NPC (Entity) Smooth Movement in Java. The entity is shaking

I have this class and I can't seem to find the answer to my question.

I'd like to create a smooth, random movement for this entity. But when I run the program, the entity goes crazy, and it continues to change direction and won't move at all (well, it moves but it shakes). How can I make it change direction more slowly?

Here's the code (and sorry for my bad english):

package praisethesun.code.entities;

import java.util.Random;

import praisethesun.code.graphics.Sprite;

public class OrganicVillager extends Organic{

    private Random direction = new Random();

    public OrganicVillager(String name, Sprite sprite, float posX, float posY, float width, float height, int speed, double velocity) {
        super(name, sprite, posX, posY, width, height, speed, velocity);    
    }

    public void update(){
        move();
    }

    private void move(){

        float moveX = 0;
        float moveY = 0;

        switch(direction.nextInt(4)) {
        case 0:
            moveY += getSpeed();
            setDirection(Direction.DOWN);

            setCurrentSprite(0,0);
            break;
        case 1:
            moveX -= getSpeed();
            setDirection(Direction.LEFT);

            setCurrentSprite(0,1);
            break;
        case 2:
            moveY -= getSpeed();
            setDirection(Direction.UP);

            setCurrentSprite(0,2);
            break;
        case 3:
            moveX += getSpeed();
            setDirection(Direction.RIGHT);

            setCurrentSprite(0,3);
            break;
        default: break;
        }

        setPosX(getPosX() + moveX);
        setPosY(getPosY() + moveY);

        setBounds((int)getPosX(), (int)getPosY());
    }
}




Aucun commentaire:

Enregistrer un commentaire