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

2020/8/8

Timestep between two frames

RcCookie RcCookie

2020/8/8

#
I have recently done a bit of Unity coding, and what I found very important that I don't have in Greenfoot is an info about the time the last frame took (--> deltaTime in Unity). This allows to have for example a constant movement speed not influenced by the framerate. I am almost certain that you can, with a bit of coding, get this timestep in Greenfoot too, but I don't know the classes and methods to do that. Maybe someone can help?
danpost danpost

2020/8/8

#
RcCookie wrote...
I have recently done a bit of Unity coding, and what I found very important that I don't have in Greenfoot is an info about the time the last frame took (--> deltaTime in Unity). This allows to have for example a constant movement speed not influenced by the framerate. I am almost certain that you can, with a bit of coding, get this timestep in Greenfoot too, but I don't know the classes and methods to do that. Maybe someone can help?
Maybe looking at the code of my Fps Actor Class scenario can help.
RcCookie RcCookie

2020/8/8

#
So this should be correct, right?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public final class Time extends greenfoot.Actor{
    private int lastMillis;
    private double deltaTime;
    public void act(){
        int currentMillis = (int)(System.currentTimeMillis() % 1000);
        if(currentMillis - lastMillis < 0)
            deltaTime = (double)(currentMillis - lastMillis + 1000) / 1000.0;
        else deltaTime = (double)(currentMillis - lastMillis) / 1000.0;
        lastMillis = currentMillis;
    }
    public double deltaTime(){
        return deltaTime;
    }
}
danpost danpost

2020/8/8

#
RcCookie wrote...
So this should be correct, right? << Code Omitted >>
Not sure why are dividing by 1000 on lines 7 and 8 (maybe you meant to get modulus of 1000). Seems like a lot being done to control roll-over. You can replace all of lines 6 thru 8 with:
1
deltaTime = (1000 + currentMillis - lastMillis) % 1000;
RcCookie RcCookie

2020/8/8

#
No the idea is to get the fraction of a second that the last frame took. That means that if you count up every frame by deltaTime the value should increase by one each second
danpost danpost

2020/8/8

#
RcCookie wrote...
No the idea is to get the fraction of a second that the last frame took. That means that if you count up every frame by deltaTime the value should increase by one each second
If I understand correctly, this should do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public final class Time
{
    private double initTime = System.currentTimeMillis();
    private double deltaTime;
 
    public void act()
    {
       deltaTime = (System.currentTimeMillis() - initTime) / 1000;
    }
     
    public double deltaTime()
    {
        return deltaTime;
    }
}
You need to login to post a reply.