This site requires JavaScript, please enable it in your browser!
Greenfoot back
Dab1001
Dab1001 wrote ...

2014/9/24

Making an Actor Shake

Dab1001 Dab1001

2014/9/24

#
In my program, I've tried to make an actor shake using Greenfoot.getRandomNumber(). My code is the following
if (((GameBackdrop) getWorld()).nervousOn)
            {
                shakeX += Greenfoot.getRandomNumber(3) - 1;
                shakeY += Greenfoot.getRandomNumber(3) - 1;
                if (shakeX > 25)
                {
                    shakeX = 24;
                }
                if (shakeX < -25)
                {
                    shakeX = -24;
                }
                if (shakeY > 25)
                {
                    shakeY = 24;
                }
                if (shakeY < -25)
                {
                    shakeY = -24;
                }
            }
setLocation(getX() + shakeX, getY() + shakeY);
However, the actor seems to shake in a single direction; it is always above and to the left of its original position, or below and to the right, never above and to the right or below and to the left. Does anyone know what might be causing this? Help is much appreciated.
danpost danpost

2014/9/24

#
This code is allowing the speed of the actor to range between 25 and -25 in both the horizontal and the vertical. The fields 'shakeX' and 'shakeY' are representing speeds along those directions. The way you adjust those speeds are what causes the slight variations in the movement -- slowly changing those speeds. I do not know if you have more movement code for this actor and cannot determine from what you have given exactly what you should do to fix it. However, a basic shake without any other movement involved would simply be:
int shakeX = Greenfoot.getRandomNumber(3)-1;
int shakeY = Greenfoot.getRandomNumber(3)-1;
setLocation(getX()+shakeX, getY()+shakeY);
Dab1001 Dab1001

2014/9/24

#
danpost wrote...
This code is allowing the speed of the actor to range between 25 and -25 in both the horizontal and the vertical. The fields 'shakeX' and 'shakeY' are representing speeds along those directions. The way you adjust those speeds are what causes the slight variations in the movement -- slowly changing those speeds. I do not know if you have more movement code for this actor and cannot determine from what you have given exactly what you should do to fix it. However, a basic shake without any other movement involved would simply be:
int shakeX = Greenfoot.getRandomNumber(3)-1;
int shakeY = Greenfoot.getRandomNumber(3)-1;
setLocation(getX()+shakeX, getY()+shakeY);
Using that, it's working now. Thanks!
You need to login to post a reply.