Initial object movement lag in applications while holding down arrow keys - algorithm

In Windows applications, when a 'movement' is associated with a key ,namely scrolling down a web page by holding down (constantly, without releasing) the arrow keys or moving the objects in a game by doing so), the movement is performed like this: first a sudden and jerky movement takes place and then after a short instance the movement continues. However, in 'Role player games' this cannot be seen and we experience a smooth movement. What is the cause of this type of movement and how can it be solved while writing a Windows application? (Note that this is seen to be regardless of programming language.)

It's not an anti-pattern. It's intentional feature: for most of the time, you need to input a single character. Only after a delay, auto-repeat kicks in, because by holding the key you have clearly expressed that you need pretty many repeats. As you need pretty many, the repeat interval is smaller than delay after a single character.
The same behavior is extended onto the cursor keys.
If there were no delay after first cursor movement, most users would have hard time moving it by 1 letter. If you need to move exactly by 3 letters, you can get a precise result by triple-pressing.
You can control the delay and repeat speed in your Control Panel's keyboard settings.
In a specific application, normally, you subscribe to KeyDown/KeyUp events and handle the repeat functionality yourself. In games, you just check if a specific cursor key is down, and get equal movement on every cycle of the main loop.

Related

how to make a key start to print immediately after i start holding c++

I am creating a kind of racing game, I have the arrow keys to move the car left and right (the up and down arrows do nothing). but when you hold left/right it takes about half a second to start going over.
here is further explanation:
so lets imagine this is my car:
O
OOO
O
OOO
and when you press <- left or -> right it moves over like it should (I have it set so it moves one space over). but when you hold it, it takes about half a second to start repeatedly moving over.
how do I make it move over immediately?
one more thing, I don't want to change the personal settings on ones computer if its possible.
thanks for answers in future.
You probably want to use either GetKeyState or GetAsyncKeyState (but more likely GetKeyState).
Either one lets you read the state of a key, so you'll call it once to see if the left arrow key is pressed, and then separately to see if the right arrow key is pressed (and if both are pressed...well, it's up to you to decide what to do in that case).
It's also up to you to decide how often to sample the current keyboard state, and how fast to react when the user holds down the key. Chances are pretty good that if you sample it as fast as possible, the car will react far too fast to control it well.

Gesture detection algorithm based on discrete points

I am trying to solve the problem of matching a human generated gesture with a known gesture. The human generated gesture will be represented by a sequence of points that will need to be interpolated into a path and compared to the existing path. The image below shows what I am trying to compare
Can you please help point me in the right direction with resources or concepts that I can read into to build an algorithm to match these two paths? I have no experience in doing this before so any insights will be appreciated.
Receiving input
Measure input on some interval. Every xx milliseconds, measure the coordinates of the user's hand/finger/stylus.
Storing patterns and input
Patterns (expected input)
Modify the pattern. It's currently a continuous "function," but measuring input as such is difficult. Use discrete points at some interval. This interval can be very short, depending on how accurate you require gestures to be. In fact, it should be very short; the more points to compare against, the better (I'll explain this a little better in the next section).
Input (received from user)
When input is measured, the input-measurement interval needs to be short enough that each received consecutive pair of input points is close enough to compare to the expected points.
Imagine that the user performs some gesture very quickly (and completes it in the time your input-reader reads only three frames). The pattern and input cannot be reliably compared:
To avoid this, your input-reader must have a relatively short interval. However, this probably isn't a huge concern, since most hardware can read even the fastest human gestures.
Back to patterns: they should always be detailed enough to include more points than any possible input. More expected points allow for better accuracy. If a user moves slowly, the input will have more points; if they move quickly, the input will have fewer.
Consider this: completing a single gesture gives you half as many input frames as the pattern includes. The user has moved at a "normal" speed, so, to simplify the algorithm, you can "dumb down" your pattern by a factor of 2, then compare input coordinates to pattern coordinates directly.
This method is easier than the alternative that comes to mind (see next section).
Pattern "density" (coordinate frequency)
If you have a small number of expected points, you'll have to make approximations to match input.
Here's an "extreme" example, but it proves the concept. Given this pattern and input:
Point 3r can't be reliably compared with point 2 or point 3, so you'd have to use some function of points 2, 3, and 3r, to determine if 3r is on the correct path. Now consider the same input, but where the pattern has higher density:
Now, you don't have to compromise, since 3r is essentially definitely on the gesture's pattern. A slight reduction in the pattern's density causes it to match input quite well.
Positioning
Relative positioning
Instead of comparing absolute positions (such as on a touchscreen), you probably want the gesture to be allowed anywhere in some plane of space. To that end, you must relate the start point of the input to some coordinate system.
Normalization
To be user-friendly, allow gestures to be done in a range of "sizes". You don't want to compare raw data, because chances are the size of the plane of the input doesn't match the size of the plane of the pattern.
Normalize the input in the x- and y-direction to match the size of your pattern. Do not maintain aspect ratio.
Relate the input to a coordinate system, as per previous bullet
Find the largest horizontal and vertical distance between any two input points (call them RecMaxH and RecMaxV)
Find the largest horizontal and vertical distance between any two pattern points (call them ExpMaxH and ExpMaxV)
Multiply all input points' x-coordinates by ExpMaxH/RecMaxH
Multiple all input points' y-coordinates by ExpMaxV/RecMaxV
You now have two more-similar sets of points that can be compared. Normalization can be much more detailed than this; for instance, you could normalize sets of 3 points at a time to get incredibly similar images (but you would probably have to do this for each pattern, then compare the sum of all differences to find the most likely matching pattern).
I suggest storing all gestures' pattern as a graph the same size; that reduces computation when measuring closeness of input to possible pattern matches.
When to measure input
User-driven
Imagine a button that, when clicked/activated, causes your program to begin measuring inputs. This would be similar to Google's Voice Search, which doesn't constantly record and search; instead, you say "Ok Jarvis" or click the handy microphone icon and begin speaking your query.
Benefits:
Simplifies algorithm
Prevents user from unintentionally triggering an event. Imagine if every word you spoke was analyzed and sent to Google as part of a search query. Sometimes you just don't mean to do anything.
Drawbacks:
Less user-friendly. User must go out of his/her way to trigger recording for gestures.
If you're writing, for instance, a gesture-search (ridiculous example), this is probably the better method to implement. Nobody wants every move they make interpreted as an action in your application. However, if you're writing a Kinect-style or gesture-based game, you probably want to be constantly recording and looking for gestures.
Constant
Your program constatly records gesture coordinates at the specified interval (this could be reduced to "records if there's movement, otherwise doesn't store coordinates"). You must make a decision: how many "frames" will you record until deciding that the currently-stored motion is not a recognized gesture?
Store coordinates in a buffer: a queue 1.5 or 2 (to be cautious) times as long as the largest number of frames you're willing to record.
Once you determine that there exists in this buffer a sequence of frames that match a pattern, execute that gesture's result, and clear the queue.
If there's the possibility that the next gesture is an "option" for the most-recent gesture, record the application state as "currently waiting on option for ____ gesture," and wait for the option to appear.
If it's determined that the first x frames in the buffer cannot possibly match a pattern (because of their sequence or positioning), remove them from the queue.
Benefits:
Allows for more dynamic handling of gestures
User input recognized automatically
Drawbacks:
More complex algorithm
Heavier computation
If you're writing a game that runs based on real-time input, this is probably the right choice.
Algorithm
If you're using user-driven recognition:
Record all input in the allowed timeframe (or until the user signifies that they're done)
To evaluate the input, reduce the density of your pattern to match that of the input
Relate the input to a coordinate system
Normalize input
Use a method of function comparison (looseness of this calculation is up to you: standard deviation, variance, total difference in values, etc.), and choose the least-different possibility.
If no possibility is similar enough to meet your required threshold (you must decide this), don't accept the input.
If you're using constant measuring:
In your buffer, treat the sequence of max_sequence_size (you decide) beginning at every multiple of frame_multiples (you decide) as a possible gesture. For instance, if all of my possible gestures are at most 20 frames long, and I believe every 5 frames a new gesture could be starting (and I won't lose any critical data in those 5 frames), I'll compare each portions of the buffer to all possible gestures (portions from 0-19, 5-24, 10-29, etc.). This is heavier computing when frame_multiples decreases. For perfect measurement, frame_multiples is 1 (but this is likely not reasonable).
Hope you've enjoyed reading this answer as much as I enjoyed writing it. I've never done this before, but you've piqued my interest in a way that doesn't often happen. Please edit and improve my answer! If there's a portion that seems incomplete, add to it. I'm very curious in (particularly, more-experienced) responses and criticism.

Falling Objects Corona

I am trying to create a falling objects game. However, I am having hard time to create level for this game. It does not change scene or anything but I want it to be harder along the way. There are bad and good items falling and the character should eat good items and avoid from bad items.
I am creating those bad and good items with a createItem function and calling this function with two timer.performWithDelay. The items are falling randomly. One for the good items and one for the bad items. However, sometimes bad item comes under the good item and it is impossible to catch the good item. How can I stop that? I added a collision filter to let those items pass through each other so that's why they come as one under the another.
Here is how I call createItem with two timers:
goodTimer = timer.performWithDelay(1000, function() createItem(goodItem[math.random(1,#goodItem)],1) end, 0 )
badTimer = timer.performWithDelay(5000, function() createItem(badItem[math.random(1,#badItem)],0) end, 0 )
If you want a deterministic behaviour (e.g., always having the option to get a good item), you would have to re-define the random layout such that it cannot affect this behaviour in any case. From your description, you are just taking collisions into account, what does not represent an accurate correction for pure randomness.
In this situation, I would:
set up a "security area" surrounding each item. For example: 2
times height/width of the given item.
make the generation of each item depend on other (existing) items. For example: before creating a good item, your algorithm should check if there is already an existing bad one which might interfere with it. That is, if, by bringing the aforementioned security area into account, there is any chance that both items would be in a situation you don't want. This analysis should be easily performed by calculating the expected collision point of the corresponding security areas under the current velocities. In case of finding out that a collision might occur, the generation of the item would be delayed, completely ignored or its type might be changed (from bad to good or vice versa).
set the collision rules but just as an in-the-safest-side post-correction, as far as most of the situations should be accounted for by the aforementioned points.

Algorithm for animating elements running across a scene

I'm not sure if the title is right but...
I want to animate (with html + canvas + javascript) a section of a road with a given density/flow/speed configuration. For that, I need to have a "source" of vehicles in one end, and a "sink" in the other end. Then, a certain parameter would determine how many vehicles per time unit are created, and their (constant) speed. Then, I guess I should have a "clock" loop, to increment the position of the vehicles at a given frame-rate. Preferrably, a user could change some values in a form, and the running animation would update accordingly.
The end result should be a (much more sophisticated, hopefully) variation of this (sorry for the blinking):
Actually this is a very common problem, there are thousands of screen-savers that use this effect, most notably the "star field", which has parameters for star generation and star movement. So, I believe there must be some "design pattern", or more widespread form (maybe even a name) for this algoritm. What would solve my problem would be some example or tutorial on how to achieve this with common control flows (loops, counters, ifs).
Any idea is much appreciated!
I'm not sure of your question, this doesn't seem an algorithm question, more like programming advice. I have a game which needs exactly this (for monsters not cars), this is what I did. It is in a sort of .Net psuedocode but similar stuff exists in other environments.
If you are running an animation by hand, you essentially need a "game-loop".
while (noinput):
timenow = getsystemtime();
timedelta = timenow - timeprevious;
update_object_positions(timedelta);
draw_stuff_to_screen();
timeprevious = timenow;
noinput = check_for_input()
The update_object_positions(timedelta) moves everything along timedelta, which is how long since this loop last executed. It will run flat-out redrawing every timedelta. If you want it to run at a constant speed, say once every 20 mS, you can stick in a thread.sleep(20-timedelta) to pad out the time to 20mS.
Returning to your question. I had a car class that included its speed, lane, type etc as well as the time it appears. I had a finite number of "cars" so these were pre-generated. I held these in a list which I sorted by the time they appeared. Then in the update_object_position(time) routine, I saw if the next car had a start time before the current time, and if so I popped cars off the list until the first (next) car had a start time in the future.
You want (I guess) an infinite number of cars. This requires only a slight variation. Generate the first car for each lane, record its start time. When you call update_object_position(), if you start a car, find the next car for that lane and its time and make that the next car. If you have patterns that you want to repeat, generate the whole pattern in one go into a list, and then generate a new pattern when that list is emptied. This would also work well in terms of letting users specify variable pattern flows.
Finally, have you looked at what happens in real traffic flows as the volume mounts? Random small braking activities cause cars behind to slightly over-react, and as the slight over-reactions accumulate it turns into cars completely stopping a kilometre back up the road. Its quite strange, and so might be a great effect in your wallpaper/screensaver whatever as well as being a proper simulation.

Stop QProgressDialog from making dock icon bounce

I have a function in my application that calls various subfunctions depending on the configuration. Each sub function is computationally intensive so I added a callback to update the status of a modal QProgressDialog. Each subfunction shows 0-100% completion of itself rather than the parent function.
If the dialog closes between subfunctions and the window doesn't have focus, the dock icon bounces. This can be seriously annoying if there are more subfunctions remaining as the user has switched focus away for a reason!
Is there a way to disable icon bouncing for when a QProgressDialog closes without focus ?
If I'm understanding correctly, the scenario you describe (even if working "correctly") leads to one of my pet peeves. That is: a progress bar which gets to the end, and then starts over at 0%. I'd rather a piece of software just say "working..." than give me an intentionally misleading progress bar!!
Why not divide your progress bar into phases, and then allocate each subfunction a section of the progress bar? In the simplest case, if you had two phases that were equal in duration you would let the first phase go from 0 to 50, and then the second phase from 50 to 100. This way you only put up and take down the progress bar once.
If the situation you have is complex, you'll need to do some pre-calculation to divide up the progress range (and a bit of ratio-oriented math). But even a crude approximation where the progress bar marches forward at an irregular speed from 0 to 100 is better than having it keep starting over!
Let's say there are three phases. The first takes a minute, the second takes two minutes, and the third takes a half hour. Sure--it would be somewhat strange to see it be 66.6% done after three minutes and then watch it slowly crunch through that last 33.3% for a half hour. But it's not as bad as going back to zero. Also, you should be able to estimate better than that. Even if something varies arbitrarily (such as an early phase reading a number N that can drastically affect a later phase)...can't you scan for that up-front? Allocate the scan maybe 5% of the time, and go from there.
If you set QProgressDialog::setAutoClose(false) the progress dialog will stay open between the subfunctions and stop the dock icon from bouncing.

Resources