I'm kinda new to the dev scene, I'm in the middle of an Android project.
I am trying to utilise the mobile phone camera flash. I'm trying to make it flash on and off in a repetitive motion. Below is a clip from my .java file.
public void clickGo(View view) {
Bundle newtempo = getIntent().getExtras();
int tempo = newtempo.getInt("tempoData");
int scaledTempo = 60000/tempo;
while (true) {
long futureTime1a = System.currentTimeMillis() + (100);
long futureTime1b = System.currentTimeMillis() + (scaledTempo - 100);
while (System.currentTimeMillis() < futureTime1a) {
setFlashlightOn();
}
while (System.currentTimeMillis() < futureTime1b) {
setFlashlightOff();
}
}
Let me explain what's going on...
So I've gained data from another activity then scaled it to a milleseconds value.
I've put the rest of the algorithm in a while(true) loop, just until I can get it working properly. I set two times, one with 100 milliseconds, and one with the scaled millesecond value MINUS the 100 milliseconds.
I then apply these two timings to turn the flash on then off.
In theory, this should work. I have data inputted from another activity which scales the number into milliseconds as shown. The concept does work, as lower numbers and higher numbers make the flash beat slower and quicker on my phone. However, the precision is my issue. When I play a click beat to the same time of the app, it's easy to tell that some flashes come in slower, or last longer.etc. I was wondering what this could possibly be? I've stripped down most of the code to a completely bare script (as I thought it could be a processing issue). It could also be the way I've implemented the time feature - if anyone else has a more efficient way, I would love to hear it!
As I said at the beginning, I'm relatively new to the dev scene, so I would appreciate it if you could answer with this in mind :)
Thank you very much!
The internal clock for computers is somewhat unreliable in quick successions like what you want. I would recommend using a timer to achieve what you want.
Related
I want to animate some text thats in an arraylist that gets changed often but I can't figure out how to animate it on the Y-Axis as it needs to move up and down and I've only set it up for obj.renderY += 10 * deltaTime but I need it to smoothly animate to the position wanted without overcomplciating it.
The current setup for animating the Y-Axis of the text is obj.renderY = (obj.renderY * (speed - 1) + offset) / speed and this is frame dependent and I haven't figured out how I would implement deltaTime into it properly most of the times I've tried it just breaks it. This current setup I have animates it to the position I want it to be on the Y-Axis even if its above or below the wanted position.
The offset is just equal to 2 + count * (fontHeight + 1) I don't know if that would help but sure I'll include it anyway. Thanks for taking your time and reading this post.
Example of trying to animate the texts movement:
float speed = 14;
obj.renderY = (obj.renderY * (speed - 1) + offset) / speed
The class that is used to get deltaTime (Updates every frame):
public class Time {
public static float deltaTime = 0;
private static long lastTime = System.nanoTime();
public static void update() {
long currentTime = System.nanoTime();
deltaTime = (currentTime - lastTime) / 1000000000.0F;
lastTime = currentTime;
}
}
Use javax.swing.Timer. It was literally built to solve this exact problem.
Timer(int delay, ActionListener listener)
delay - Place the amount of time you want the timer to wait before kicking things off. Please note - this does NOT mean the amount of time between each task, only the amount of time before starting each task.
listener - Place your actual task here.
Then, all you need to do is use the start() method, and that should be it. You can configure the timer in other ways, but that is the basics.
EDIT - I imagine that many people who are asking this question are game developers trying to make some part of their game run at 60 frames per second.
You can use a timer, but you might be better off using something from a game engine instead.
In short, you probably want something more feature rich than a simple timer. Timers are effective, but they can be hard to manage, and may not kick off at the exact frame that you want them to, leading to issues. Timers are meant to be a simple tool to make kicking off a task at a certain frequency easier. But it's rarely as simple as that when making a game.
I would discourage you from using this timer for anything other than a basic repetitive task that only needs to start and stop after a certain event. If you want something with precision, stick to using the tools found in some of your game engines. They specialize in getting certain actions to kick off at the exact times you want them to.
Hello everyone,
I am quite new to Flutter and wanted to build an application that detects multiple touches and if that touch lasts longer sets a circle there for example.
Similar to this there is the app "Chwazi Finger Chooser" in the PlayStore. This is how the whole thing should look like in the end.
Can you help me and tell me which components I need? Or if possible suggest some code?
I have not found an answer through my research so far and am hoping for you now!
Please help me :)
check the GestureDetector widget
and those available events https://flutter.dev/docs/development/ui/advanced/gestures
however Using OnGestureListener to detect multitouch gestures does not seem to be implemented by default.
The first thing you may have tried is reading event.pointerCount to get the count of fingers on the screen. However, this will be equal to 1. This is because you will (quite likely) never be able touch the screen with both fingers in exactly the same millisecond.
Fixing it
You have to buffer pointerCount (the amount of fingers on screen). First add those variables somewhere in the context that you intend to track gestures in:
// track how many fingers are used
var bufferedPointerCount = 1
var bufferTolerance = 500 // in ms
var pointerBufferTimer = Timer()
Then, in the onTouchEvent(event: MotionEvent) function, you add this:
// Buffer / Debounce the pointer count
if (event.pointerCount > bufferedPointerCount) {
bufferedPointerCount = event.pointerCount
pointerBufferTimer = fixedRateTimer("pointerBufferTimer", true, bufferTolerance, 1000) {
bufferedPointerCount = 1
this.cancel() // a non-recurring timer
}
}
Essentially this tracks the maximum amount of fingers on the display and keeps it valid for bufferTolerance milliseconds (here: 500).
I'm creating a little game as a project for my studies using Java with Libgdx.
The game is really simple: 2D, side view, controled with the arrowpad and everything is seen like in a grid divided in units (player is 1 unit tall, environment tides are 1 unit tall, ...).
The problem is that the movement of the character is quick (and it has to be) so it's really hard to move only 1 unit to the left or to the right.
I was wondering if it's possible to create a delay between two inputs from the keyboard because the movement part is in an "update" method so everytime I press a key it creates like 5 or 10 inputs.
I tried to handle it with java timers (like 0.2 or 0.3 sec) that happened everytime I press a key and unable the programm to listen to the keyboard until the timer is done. But I find it really dirty so i'm asking for your help to lead me on a more decent way to do this. Thanks.
You can easily implement a cooldown kind of thing, by comparing the last time of use by the current time.
double coolDownInMillis = 1200;
double lastTime = 0;
public void move() {
double now = System.currentTimeMillis();
if(lastTime - now > coolDownInMillis && pressingTheRightKey()){
//do what you want
lastTime = System.currentTimeMillis();
}
}
Or something like this.
I am developing a game, and just wanted to test it on a different computer to check if the resolutions are ok and all that stuff but noticed one big problem, the game runs in slow motion for some reason... Not laggy, but slow motion..
My game loop is a temporary:
while(gameisRunnin){
doStuff();
Thread.sleep(1000/60);
But after the test, I've tried to check how much time does it take to do the doStuff(); code and I tested it like this:
while(gameisRunnin){
long startT = System.currentTimeMillis();
doStuff();
long stopT = System.currentTimeMillis();
System.out.println(stopT-startT);
Thread.sleep(1000/60);
The result it gives me is 0, on both computers, (On the one I am developing the game which runs in the perfect speed, and on the pc that it runs in slow motion..
Also I tested it with nano time, it gives me like 50000-80000 on both computes too (pretty much same result.
Seriously what's up? Could a superman save me?
UPDATE:
Ok so when I run the game on the other computer NOT on full screen, it's runs fine, but when it is on full screen, it's slowmotion
Update:
Looks like I am the superhero here, I've set the displaymode the refresh rate to unknown, I guess that was the whole problem...
You've to use something what is usually called "delta time". Basically it means, that you measure how long it takes to do one iteration of the game loop and then use this number for all the movements.
This is because of the different count of FPS on different computers. Instead of moving objects for just constant amount of pixels, you're defining speed and calculating the actual size of movement dynamically.
Short example:
public void gameLoop() {
long initialTime = System.nanoTime();
game.redraw();
game.update(System.nanoTime() - initialTime);
}
// inside the class Game
public void update(long deltaTime) {
someObject.moveToRight(deltaTime * speed);
}
The answer is that the refresh rate of the game wasn't supported by the monitor, changing the refresh-rate from 60 to DisplayMode.REFRESH_RATE_UNKNOWN fixes the slowmotion problem.
Read this article: click here
Also, as a side note, use System.nanoTime() because System.getTimeMillis() isn't as accurate.
I have problems with smooth scrolling in OpenGL (testing on SGS2 and ACE)
I created simple applications - only fixed speed horizontal scrolling of images, or only one image (player) moving by accelerator,
but it's movement is not smooth :-(
I tried many various of code but no satisfaction...
first I tried work with GLSurfaceView.RENDERMODE_CONTINUOUSLY and I put all code to onDrawFrame:
public void onDrawFrame(GL10 gl)
{
updateGame(gl, 0.017f);
drawGame(gl);
}
this is the simplest and absolute smooth!! - but it's dependent on hardware speed (= useless)
public void onDrawFrame(GL10 gl)
{
frameTime = SystemClock.elapsedRealtime();
elapsedTime = (frameTime - lastTime) / 1000;
updateGame(gl, elapsedTime);
drawGame(gl);
lastTime = frameTime;
}
this is the best of all but it's not as smooth as the previous, sometimes flick
second I tried GLSurfaceView.RENDERMODE_WHEN_DIRTY, in onDrawFrame i have only drawing objects and this code in separate Thread:
while (true)
{
updateGame(renderer, 0.017f);
mGLSurfaceView.requestRender();
next_game_tick += SKIP_TICKS;
sleep_time = next_game_tick - System.currentTimeMillis();
if (sleep_time >= 0)
{
try
{
Thread.sleep(sleep_time);
}
catch (Exception e) {}
}
else
{
Log.d("running behind: ", String.valueOf(sleep_time));
}
}
this is not smooth and it's not problem with "running behind"
My objective is smooth image movement like in first code example above.
Possible error is somewhere else then I looking. Please, Can somebody help me with this?
Is better use RENDERMODE_WHEN_DIRTY or RENDERMODE_CONTINUOUSLY?
Thank you.
I was fighting with the exact same issue for several days. The loop looks smooth without any Android time reference, but as soon it includes any type of “time sync” , external factors out of the android development control introduce serious discontinuities to the final result.
Basically, these factors are:
eglSwapInterval is not implemented in Android, so is difficult to know the moment when the hardware expose the final draw in the screen (hardware screen sync)
Thread.sleep is not precise. The Thread may sleep more or less than requested.
SystemClock.uptimeMillis()System.nanoTime(), System.currentTimeMillis() and other timing related measurement are not accurate (its precise).
The issue is independent of the drawing technology (drawing, openGL 1.0/1.1 and 2.0) and the game loop method (fixed time step, interpolation, variable time step).
Like you, I was trying Thread.sleep, crazy interpolations, timers, etc. Doesn’t matter what you will do, we don’t have control over this factors.
According with many Q&A on this site, the basic rules to produce smooth continuous animations are:
Reduce at the minimum the GC by removing all dynamic memory request.
Render frames as fast the hardware can process them (40 to 60fps is ok in most android devices).
Use fixed time steps with interpolation or variable time steps.
Optimize the update physics and draw routines to be execute in relative constant time without high peaks variance.
For sure, you made a lot of previous work before post this question by optimizing your updateGame() and drawGame() (without appreciable GC and relative constant execution time) in order to get a smooth animation in your main loop as you mention: “simple and absolute smooth”.
Your particular case with variable stepTime and no special requirements to be in perfect sync with realTime events (like music), the solution is simple: “smooth the step Time variable”.
The solution works with other game loop schemes (fixed time step with variable rendering) and is easy to port the concept (smooth the amount of displacement produced by the updateGame and the real time clock across several frames.)
// avoid GC in your threads. declare nonprimitive variables out of onDraw
float smoothedDeltaRealTime_ms=17.5f; // initial value, Optionally you can save the new computed value (will change with each hardware) in Preferences to optimize the first drawing frames
float movAverageDeltaTime_ms=smoothedDeltaRealTime_ms; // mov Average start with default value
long lastRealTimeMeasurement_ms; // temporal storage for last time measurement
// smooth constant elements to play with
static final float movAveragePeriod=40; // #frames involved in average calc (suggested values 5-100)
static final float smoothFactor=0.1f; // adjusting ratio (suggested values 0.01-0.5)
// sample with opengl. Works with canvas drawing: public void OnDraw(Canvas c)
public void onDrawFrame(GL10 gl){
updateGame(gl, smoothedDeltaRealTime_ms); // divide 1000 if your UpdateGame routine is waiting seconds instead mili-seconds.
drawGame(gl);
// Moving average calc
long currTimePick_ms=SystemClock.uptimeMillis();
float realTimeElapsed_ms;
if (lastRealTimeMeasurement_ms>0){
realTimeElapsed_ms=(currTimePick_ms - lastRealTimeMeasurement_ms);
} else {
realTimeElapsed_ms=smoothedDeltaRealTime_ms; // just the first time
}
movAverageDeltaTime_ms=(realTimeElapsed_ms + movAverageDeltaTime_ms*(movAveragePeriod-1))/movAveragePeriod;
// Calc a better aproximation for smooth stepTime
smoothedDeltaRealTime_ms=smoothedDeltaRealTime_ms +(movAverageDeltaTime_ms - smoothedDeltaRealTime_ms)* smoothFactor;
lastRealTimeMeasurement_ms=currTimePick_ms;
}
// Optional: check if the smoothedDeltaRealTIme_ms is too different from original and save it in Permanent preferences for further use.
For a fixed time step scheme, an intermetiate updateGame can be implemented to improve the results:
float totalVirtualRealTime_ms=0;
float speedAdjustments_ms=0; // to introduce a virtual Time for the animation (reduce or increase animation speed)
float totalAnimationTime_ms=0;
float fixedStepAnimation_ms=20; // 20ms for a 50FPS descriptive animation
int currVirtualAnimationFrame=0; // useful if the updateGameFixedStep routine ask for a frame number
private void updateGame(){
totalVirtualRealTime_ms+=smoothedDeltaRealTime_ms + speedAdjustments_ms;
while (totalVirtualRealTime_ms> totalAnimationTime_ms){
totalAnimationTime_ms+=fixedStepAnimation_ms;
currVirtualAnimationFrame++;
// original updateGame with fixed step
updateGameFixedStep(currVirtualAnimationFrame);
}
float interpolationRatio=(totalAnimationTime_ms-totalVirtualRealTime_ms)/fixedStepAnimation_ms;
Interpolation(interpolationRatio);
}
Tested with canvas and openGlES10 drawing with the following devices: SG SII (57 FPS), SG Note(57 FPS) , SG tab(60 FPS), unbranded Android 2.3 (43 FPS) slow emulator running on Windows XP(8 FPS). The test platform draws around 45 objects + 1 huge background (texture from 70MP source image) moving along a path specified in real physics parameters (km/h and G’s), without spikes or flick between several devices (well, 8 FPS on the emulator doesn’t look good, but its flow at constant speed as expected)
Check The graphs for how android report the time. Some times Android report a large delta time and just the next loop it's small than average, meaning an offset on the reading of realTime value.
with more detail:
How to limit framerate when using Android's GLSurfaceView.RENDERMODE_CONTINUOUSLY?
System.currentTimeMillis vs System.nanoTime
Does the method System.currentTimeMillis() really return the current time?