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

2013/5/13

platform shaking effect

ronzhi ronzhi

2013/5/13

#
Hi, i'm trying to create shaking effect with the ground with this
public void addedToWorld(World world)
    {
        center=getX();
    } 

public void act() 
    {
         setLocation(center+5, getY());
         Greenfoot.delay(1);
         setLocation(center-5, getY());
         Greenfoot.delay(1);
}
but the delay is so much affected the whole gameplay. how to create shaking effect without delay method?
danpost danpost

2013/5/13

#
Add an instance int shakeTimer field to the class:
// add this instance field
private int shakeTimer;
// the act method
public void act()
{
    shakeTimer = (shakeTimer+1)%4; // value changes 0>1>2>3>0>1>2>3>0>1...
    if (shakeTimer%2==0) setLocation(getX()+5*(1-shakeTimer), getY());
}
The 'if' block only executes when 'shakeTimer' is zero or two (every other act cycle). The value of '1-shakeTimer' will then be either one or negative one, effectively alternating the direction of the shake. You can remove the 'addedToWorld' method (and the 'center' field declaration); as they are not necessary.
ronzhi ronzhi

2013/5/13

#
works like a charm, and btw is that kind of well-known algo or you just think it out of yourself?
danpost danpost

2013/5/13

#
The above probably shakes way to quick. I will add another instance field to help slow it down.
// with instance fields
private int shakeTimer;
private final int shakeFreq = 10; // any positive even number 
// and this act method
public void act()
{
    shakeTimer = (shakeTimer+1)%shakeFreq;
    if (shakeTimer%(shakeFreq/2) == 0) setLocation(getX()+5*(1-4*shakeTimer/shakeFreq), getY());
}
danpost danpost

2013/5/13

#
I have never really 'copied' code. Over time, it is basically what I have gotten used to doing (I was always pretty good with the Maths).
ronzhi ronzhi

2013/5/13

#
wow it's even better than before, you rock ! great thanks danpost
You need to login to post a reply.