Does Phaser Arcade.Body velocity include deltaTime or not? - phaser-framework

I want to move my character along the x axis with constantly speed. I thought move depends on frame rate. So, technically I should write
sprite.body.velocity.x = speed * deltaTime
where deltaTime = game.time.elapsedMS / 1000;
But if I'm doing that - my character moves vvvvverrry slooow, even if speed = 1000.
But if I'm writing
sprite.body.velocity.x = speed
it works fine. My fps = 60;
Phaser Documentation
says:
velocity - The velocity, or rate of change in speed of
the Body. Measured in pixels per second.
no deltatime....
and all demos do not have deltatime
http://phaser.io/examples/v2/arcade-physics/platformer-basics
http://phaser.io/examples/v2/arcade-physics/asteroids-movement
etc.
So, I don't understand: shoud I calculate deltaTime or just use velocity.x?

Well.... I think I'm stupid...
My calculation of the deltaTime was wrong
The correct formula will be
deltaTime = (elapsedMS * fps) / 1000
elapsedMS - The time in ms since the last time update, in milliseconds, based on time.
fps - Frames per second.
(Only calculated if advancedTiming is enabled).
So, that was my problem.
As the result
body.velocity doesn't include calculation of deltaTime and for smooth movement should use deltaTime that calculated by the formula above.
And it will be something like that
function update() { // <-- it is phaser state method...is called every frame
deltaTime = (elapsedMS * fps) / 1000;
sprite.body.velocity.x = velocityX * deltaTime;
sprite.body.velocity.y = velocityY * deltaTime;
}

Related

Wrong timing in physics simulation with piston

I have written a very basic simulation of a pendulum. I used the equation α = -g/l * sin(φ). I set g/l to 50, so I expect to get a period of 0.89 seconds (Using the formula 2π*√(l/g)). However, I get a period of around 6.5 seconds. The relevant code part is
let ang_acc = - 50.0 * pendulum.angle.to_radians().sin();
pendulum.ang_vel += ang_acc * dt;
pendulum.angle += pendulum.ang_vel * dt;
The complete code is on GitHub. I tried to make it as basic as possible and commented everything important.

Is there any NodeJs class/function which is similar to Environment.TickCount on c#?

This code is running on c#
int x = Environment.TickCount;
docs for Environment.TickCount
Gets the number of milliseconds elapsed since the system started. TickCount cycles between Int32.MinValue, which is a negative number, and Int32.MaxValue once every 49.8 days.
TickCount will increment from Zero to (2147483647) for approximately 24.9 days, then jump back to (-2147483648), which is a negative number, then increment back to zero during the next 24.9 days.
We can use int result = Environment.TickCount & Int32.MaxValue; to make it rotate between (0) and (2147483647) for every 24.9 days
I want an equivalent method in NodeJS, which would yield the same result.
I made a search on NodeJS npmjs but didn't find similar function
os.uptime() is the closest method to what you need which
Returns the system uptime in number of seconds
NodeJS docs
But this is a valid question that what will be the max limit for the above method.?
In NodeJS the max safe integer is Number.MAX_SAFE_INTEGER that is 9007199254740991. Which is basically 289583309.373 years. So I guess we will have to assume this as the max value for said method.
If you want the functionality as of c#'s TickCount, you will need to create your own custom method, maybe something like given below:
// this method will cycle between 0 and 2147483647
function TickCount() {
const miliseconds_elapsed = os.uptime() * 1000; // convert the time in miliseconds
return miliseconds_elapsed % 2147483647;
}
// this method will cycle between -2147483648 to 2147483647
// note: it will not start from 0
function TickCount() {
const miliseconds_elapsed = os.uptime() * 1000; // convert the time in miliseconds
return (miliseconds_elapsed % 4294967296) - 2147483648;
}
// this method will cycle between -2147483648 to 2147483647
// note: it will start from 0 goes to 2147483647
// then comes back to -2147483648 and starts the cycle
function TickCount() {
const miliseconds_elapsed = os.uptime() * 1000; // convert the time in miliseconds
if (miliseconds_elapsed <= 2147483647) {
return miliseconds_elapsed;
}
return ((miliseconds_elapsed - 2147483648) % 4294967296) - 2147483648;
}
The Microsoft docs say Environment.TickCount is an integer that "contains the amount of time in milliseconds that has passed since the last time the computer was started".
When searching for that I found this question and the answers suggest to use process.uptime() oros.uptime()

Calculate approximated distance using RSSI

I working on a project that aims to measure approximated distance between single Raspberry PI and nearby smartphone.
The final target of the project is to check if there is a smartphone in the same room of the Raspberry.
I thought on two ways for implementation. The first is measure distance using RSSI value, second is to calibrate the setup in the first time from many places in the room and outside the room and get a threshold RSSI value.
I read that smartphones sends wi-fi packets even when the wi-fi is disabled, I thought to use this feature the get the RSSI value from the transmitting smartphone (Using kismet passively) and check if its in the room. I can use Bluetooth RSSI also.
How can I calculate distance using RSSI?
This is an open issue. Basically, Measuring distance according to the RSSI in the ideal state is easy, The main challenge is reducing noise that produced due to multipath and reflecting RF signals and its Interferences. Anyway, you can convert RSSI to distance by below code:
double rssiToDistance(int RSSI, int txPower) {
/*
* RSSI in dBm
* txPower is a transmitter parameter that calculated according to its physic layer and antenna in dBm
* Return value in meter
*
* You should calculate "PL0" in calibration stage:
* PL0 = txPower - RSSI; // When distance is distance0 (distance0 = 1m or more)
*
* SO, RSSI will be calculated by below formula:
* RSSI = txPower - PL0 - 10 * n * log(distance/distance0) - G(t)
* G(t) ~= 0 //This parameter is the main challenge in achiving to more accuracy.
* n = 2 (Path Loss Exponent, in the free space is 2)
* distance0 = 1 (m)
* distance = 10 ^ ((txPower - RSSI - PL0 ) / (10 * n))
*
* Read more details:
* https://en.wikipedia.org/wiki/Log-distance_path_loss_model
*/
return pow(10, ((double) (txPower - RSSI - PL0)) / (10 * 2));
}

Is there a more efficient way of texturing a circle?

I'm trying to create a randomly generated "planet" (circle), and I want the areas of water, land and foliage to be decided by perlin noise, or something similar. Currently I have this (psudo)code:
for (int radius = 0; radius < circleRadius; radius++) {
for (float theta = 0; theta < TWO_PI; theta += 0.1) {
float x = radius * cosine(theta);
float y = radius * sine(theta);
int colour = whateverFunctionIMake(x, y);
setPixel(x, y, colour);
}
}
Not only does this not work (there are "gaps" in the circle because of precision issues), it's incredibly slow. Even if I increase the resolution by changing the increment to 0.01, it still has missing pixels and is even slower (I get 10fps on my mediocre computer using Java (I know not the best) and an increment of 0.01. This is certainly not acceptable for a game).
How might I achieve a similar result whilst being much less computationally expensive?
Thanks in advance.
Why not use:
(x-x0)^2 + (y-y0)^2 <= r^2
so simply:
int x0=?,y0=?,r=?; // your planet position and size
int x,y,xx,rr,col;
for (rr=r*r,x=-r;x<=r;x++)
for (xx=x*x,y=-r;y<=r;y++)
if (xx+(y*y)<=rr)
{
col = whateverFunctionIMake(x, y);
setPixel(x0+x, y0+y, col);
}
all on integers, no floating or slow operations, no gaps ... Do not forget to use randseed for the coloring function ...
[Edit1] some more stuff
Now if you want speed than you need direct pixel access (in most platforms Pixels, SetPixel, PutPixels etc are slooow. because they perform a lot of stuff like range checking, color conversions etc ... ) In case you got direct pixel access or render into your own array/image whatever you need to add clipping with screen (so you do not need to check if pixel is inside screen on each pixel) to avoid access violations if your circle is overlapping screen.
As mentioned in the comments you can get rid of the x*x and y*y inside loop using previous value (as both x,y are only incrementing). For more info about it see:
32bit SQRT in 16T without multiplication
the math is like this:
(x+1)^2 = (x+1)*(x+1) = x^2 + 2x + 1
so instead of xx = x*x we just do xx+=x+x+1 for not incremented yet x or xx+=x+x-1 if x is already incremented.
When put all together I got this:
void circle(int x,int y,int r,DWORD c)
{
// my Pixel access
int **Pixels=Main->pyx; // Pixels[y][x]
int xs=Main->xs; // resolution
int ys=Main->ys;
// circle
int sx,sy,sx0,sx1,sy0,sy1; // [screen]
int cx,cy,cx0, cy0 ; // [circle]
int rr=r*r,cxx,cyy,cxx0,cyy0; // [circle^2]
// BBOX + screen clip
sx0=x-r; if (sx0>=xs) return; if (sx0< 0) sx0=0;
sy0=y-r; if (sy0>=ys) return; if (sy0< 0) sy0=0;
sx1=x+r; if (sx1< 0) return; if (sx1>=xs) sx1=xs-1;
sy1=y+r; if (sy1< 0) return; if (sy1>=ys) sy1=ys-1;
cx0=sx0-x; cxx0=cx0*cx0;
cy0=sy0-y; cyy0=cy0*cy0;
// render
for (cxx=cxx0,cx=cx0,sx=sx0;sx<=sx1;sx++,cxx+=cx,cx++,cxx+=cx)
for (cyy=cyy0,cy=cy0,sy=sy0;sy<=sy1;sy++,cyy+=cy,cy++,cyy+=cy)
if (cxx+cyy<=rr)
Pixels[sy][sx]=c;
}
This renders a circle with radius 512 px in ~35ms so 23.5 Mpx/s filling on mine setup (AMD A8-5500 3.2GHz Win7 64bit single thread VCL/GDI 32bit app coded by BDS2006 C++). Just change the direct pixel access to style/api you use ...
[Edit2]
to measure speed on x86/x64 you can use RDTSC asm instruction here some ancient C++ code I used ages ago (on 32bit environment without native 64bit stuff):
double _rdtsc()
{
LARGE_INTEGER x; // unsigned 64bit integer variable from windows.h I think
DWORD l,h; // standard unsigned 32 bit variables
asm {
rdtsc
mov l,eax
mov h,edx
}
x.LowPart=l;
x.HighPart=h;
return double(x.QuadPart);
}
It returns clocks your CPU has elapsed since power up. Beware you should account for overflows as on fast machines the 32bit counter is overflowing in seconds. Also each core has separate counter so set affinity to single CPU. On variable speed clock before measurement heat upi CPU by some computation and to convert to time just divide by CPU clock frequency. To obtain it just do this:
t0=_rdtsc()
sleep(250);
t1=_rdtsc();
fcpu = (t1-t0)*4;
and measurement:
t0=_rdtsc()
mesured stuff
t1=_rdtsc();
time = (t1-t0)/fcpu
if t1<t0 you overflowed and you need to add the a constant to result or measure again. Also the measured process must take less than overflow period. To enhance precision ignore OS granularity. for more info see:
Measuring Cache Latencies
Cache size estimation on your system? setting affinity example
Negative clock cycle measurements with back-to-back rdtsc?

gstreamer read decibel from buffer

I am trying to get the dB level of incoming audio samples. On every video frame, I update the dB level and draw a bar representing a 0 - 100% value (0% being something arbitrary such as -20.0dB and 100% being 0dB.)
gdouble sum, rms;
sum = 0.0;
guint16 *data_16 = (guint16 *)amap.data;
for (gint i = 0; i < amap.size; i = i + 2)
{
gdouble sample = ((guint16)data_16[i]) / 32768.0;
sum += (sample * sample);
}
rms = sqrt(sum / (amap.size / 2));
dB = 10 * log10(rms);
This was adapted to C from a code sample, marked as the answer, from here. I am wondering what it is that I am missing from this very simple equation.
Answered: jacket was correct about the code loosing the sign, so everything ended up being positive. Also the code 10 * log(rms) is incorrect. It should be 20 * log(rms) as I am converting amplitude to decibels (as a measure of outputted power).
The level element is best for this task (as #ensonic already mentioned) its intended for exactly what you need..
So basically you add to your pipe element called "level", then enable the messages triggering.
Level element then emits messages which contains values of RMS Peak and Decay. RMS is what you need.
You can setup callback function connected to such message event:
audio_level = gst_element_factory_make ("level", "audiolevel");
g_object_set(audio_level, "message", TRUE, NULL);
...
g_signal_connect (bus, "message::element", G_CALLBACK (callback_function), this);
bus variable is of type GstBus.. I hope you know how to work with buses
Then in callback function check for the element name and get the RMS like is described here
There is also normalization algorithm with pow() function to convert to value between 0.0 -> 1.0 which you can use to convert to % as you stated in your question.

Resources