Unit of measurement in a game physics engine - android

in my game I get the acceleration from the accelerometer.
Computing my calculation, I have to apply a coefficient to turn unit of measurementin pixel unit.
I apply the coefficient founded for an Android app (in a sample):
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mXDpi = metrics.xdpi;
mYDpi = metrics.ydpi;
mMetersToPixelsX = mXDpi / 0.0254f;
mMetersToPixelsY = mYDpi / 0.0254f;
to my acceleration, getting pixels/s^2. in this way i can use pixel everywhere in my code instead of thinking all in meters.
It is right?

It's going to depend on what sort of physics you want to impose. (This assumes you want Newtonian mechanics.) If you want to track the motion of the device, then you need to integrate the acceleration to get velocity and then integrate the velocity to get position. Or I suppose, you could skip the intermediate step and translate from 'acceleration' to change in position by using 0.5*acceleration^2 (and then multiply that result by an appropriate scaling factor that you will probably need to determine by experiment). (That second method may not properly handle constant motion.) For each independent dimension, velocity and position would be a cumulative sum with these recurrence relations:
velocity[t] = acceleration[t] *(t -(t-1) ) + velocity[t-1]
position[t] = position[t-1] + velocity[t]*(t -(t-1) )

Related

Android accelerometer calibration?

TL;DR
How come the accelerometer values I get from Sensor.TYPE_ACCELEROMETER are slightly offset? I don't mean by gravity, but by some small error that varies from axis to axis and phone to phone.
Can I calibrate the accelerometer? Or is there a standard way of compensating for these errors?
I'm developing an app that has a need for as precise acceleration measurements as possible (mainly vertical acceleration, i.e. same direction as gravity).
I've been doing A LOT of testing, and it turns out that the raw values I get from Sensor.TYPE_ACCELEROMETER are off. If I let the phone rest at a perfectly horizontal surface with the screen up, the accelerometer shows a Z-value of 9.0, where it should be about 9.81. Likewise, if I put the phone in portrait or landscape mode, the X- and Y- accelerometer values show about 9.6. instead of 9.81.
This of course affects my vertical acceleration, as I'm using SensorManager.getRotationMatrixFromVector(), to calculate the vertical acceleration, resulting in a vertical acceleration that is off by a different amount depending on the rotation of the device.
Now, before anyone jumps the gun and mentions that I should try using Sensor.TYPE_LINEAR_ACCELERATION instead, I must point out that I'm actually doing that as well, parallel to the TYPE_ACCELERATION. By using the gravity sensor I then calculate the vertical acceleration (as described in this answer). The funny thing is that I get EXACTLY the same result as the method that uses the raw accelerometer, SensorManager.getRotationMatrixFromVector() and matrix multiplication (and finally subtracting gravity).
The only way I'm able to get almost exactly zero vertical acceleration for a stationary phone in any rotation is to get the raw accelerometer values, add an offset (from earlier observations, i.e. X+0.21, Y+0.21 and Z+0.81) and then performing the rotation matrix stuff to get the world coordinate system accelerations. Note that since it's not just the calculated vertical acceleration that is wrong - it's actually the raw values from Sensor.TYPE_ACCELEROMETER, which I would think excludes other error sources like gyroscope sensor, etc?
I have tested this on two different phones (Samsung Galaxy S5 and Sony Xperia Z3 compact), and both have these accelerometer value deviances - but of course not the same values on both phones.
How come the the values of Sensor.TYPE_ACCELEROMETER are off, and is there a better way of "calibrating" the accelerometer than simply observing how much they deviate from gravity and adding the difference to the values before using them?
You should calibrate gains, offsets, and angle of the 3 accelerometers.
Unfortunately it's not possible to deepen the whole topic here.
I'll write a small introduction, describing the basic concept, and then I'll post a link to the code of a simple Clinometer that implements the calibration.
The calibration routine could be done with 7 misurations (calculate the mean value of a good number of samples) in different ortogonal positions at your choice, in order to have all +-0 and +-g values of your accelerometers. For example:
STEP 1 = Lay flat
STEP 2 = Rotate 180°
STEP 3 = Lay on the left side
STEP 4 = Rotate 180°
STEP 5 = Lay vertical
STEP 6 = Rotate 180° upside-down
STEP 7 = Lay face down
Then you can use the 7 measurements mean[][] to calculate offsets and gains:
calibrationOffset[0] = (mean[0][2] + mean[0][3]) / 2;
calibrationOffset[1] = (mean[1][4] + mean[1][5]) / 2;
calibrationOffset[2] = (mean[2][0] + mean[2][6]) / 2;
calibrationGain[0] = (mean[0][2] - mean[0][3]) / (STANDARD_GRAVITY * 2);
calibrationGain[1] = (mean[1][4] - mean[1][5]) / (STANDARD_GRAVITY * 2);
calibrationGain[2] = (mean[2][0] - mean[2][6]) / (STANDARD_GRAVITY * 2);
using the values of mean[axis][step], where STANDARD_GRAVITY = 9.81.
Then apply the Gain and Offset Corrections to measurements:
for (int i = 0; i < 7; i++) {
mean[0][i] = (mean[0][i] - calibrationOffset[0]) / calibrationGain[0];
mean[1][i] = (mean[1][i] - calibrationOffset[1]) / calibrationGain[1];
mean[2][i] = (mean[2][i] - calibrationOffset[2]) / calibrationGain[2];
}
and finally calculates the correction angles:
for (int i = 0; i < 7; i++) {
angle[0][i] = (float) (Math.toDegrees(Math.asin(mean[0][i]
/ Math.sqrt(mean[0][i] * mean[0][i] + mean[1][i] * mean[1][i] + mean[2][i] * mean[2][i]))));
angle[1][i] = (float) (Math.toDegrees(Math.asin(mean[1][i]
/ Math.sqrt(mean[0][i] * mean[0][i] + mean[1][i] * mean[1][i] + mean[2][i] * mean[2][i]))));
angle[2][i] = (float) (Math.toDegrees(Math.asin(mean[2][i]
/ Math.sqrt(mean[0][i] * mean[0][i] + mean[1][i] * mean[1][i] + mean[2][i] * mean[2][i]))));
}
calibrationAngle[2] = (angle[0][0] + angle[0][1])/2; // angle 0 = X axis
calibrationAngle[1] = -(angle[1][0] + angle[1][1])/2; // angle 1 = Y axis
calibrationAngle[0] = -(angle[1][3] - angle[1][2])/2; // angle 2 = Z axis
You can find a simple but complete implementation of a 3-axis calibration in this opensource Clinometer app: https://github.com/BasicAirData/Clinometer.
There is also the APK and the link of the Google Play Store if you want to try it.
You can find the calibration routine in CalibrationActivity.java;
The calibration parameters are applied in ClinometerActivity.java.
Furthermore, you can find a very good technical article that deepens the 3-axis calibration here: https://www.digikey.it/it/articles/using-an-accelerometer-for-inclination-sensing.

MATLAB when integrating from acceleration to velocity to position I am getting very high y values

I am getting raw acceleration data from an accelerometer and am trying to double integrate it in order to get the position.
The android phone used to get the data is set on a flat surface for 3 seconds to diminish drift. I take the mean of acceleration over the resting period to zero out the beginning. This worked out fine, but when we integrate to velocity and position (using cumtrapz) we are getting unrealistically high y values (meters/s for velocity and meters for position.)
The raw data is waving the phone at a certain tempo.
Does anyone have ideas on why the position gets such high values?
Below are the graphs showing what I described as well as my code.
Edit: Even when the phones is not rotated, the values are unrealistic and not indicative of how the phone moved. In the attached pictures, the phone was moved in the shape of a box on a flat surface with no rotation involved.
%VarName2 = accelerometer values in X direction
%VarName3 = accelerometer values in Y direction
%VarName4 = accelerometer values in Z direction
%elapsedArray = time values for each sample of accelerometer data
ddx = VarName2 - mean(VarName2(1:limit));
ddx = ddx(1:length(ddx)-200);
elapsedArray = elapsedArray(1:length(elapsedArray)-200);
ddy = VarName3 - mean(VarName3(1:limit));
ddy = ddy(1:length(ddy)-200);
ddz = VarName4 - mean(VarName4(1:limit));
ddz = ddz(1:length(ddz)-200);
velX = cumtrapz(ddx .* elapsedArray);
velY = cumtrapz(ddy .* elapsedArray);
velZ = cumtrapz(ddz .* elapsedArray);
dx = velX - mean(velX(1:limit));
dy = velY - mean(velY(1:limit));
dz = velZ - mean(velZ(1:limit));
posX = cumtrapz(dx .* elapsedArray);
posY = cumtrapz(dy .* elapsedArray);
posZ = cumtrapz(dz .* elapsedArray);
x = posX - mean(posX(1:limit));
y = posY - mean(posY(1:limit));
z = posZ - mean(posZ(1:limit));
figure;
plot(ddx);
title('Acceleration in X')
xlabel('Time (sec)')
ylabel('Acc (meters squared');
figure;
plot(dx);
title('Velocity in X')
xlabel('Time (sec)')
ylabel('Velocity (meters)');
figure;
plot(x);
title('Position X')
xlabel('Time (sec)')
ylabel('Position (meters)');
figure;
plot(y);
title('Position Y')
xlabel('Time (sec)')
ylabel('Position (meters)');
figure;
plot(z);
title('Position Z')
xlabel('Time (sec)')
ylabel('Position (meters)');
Acceleration in X direction
Velocity and Position in X direction
What you are seeing is the result of time drift. Let's assume that the accelerometer readings you are measuring have a very small error, dErr, at every time point. Once you integrate these values to get velocity, the error at each time point will be multiplied by a factor t. Integrating a second time to get position will cause the original error to be multiplied by a factor of t^2. Therefore, the error at each time point will propogate at dErr(t)*t^2.
In order to get a good estimate for position, you can try to incorporate prior information about position, but will likely have to use a combination of accelerometer and gyroscope data. You might also have to look into Kalman Filters.
Here is a Google Tech Talk explaining this issue:
https://youtu.be/C7JQ7Rpwn2k?t=23m33s

How to make TMXTiledMap responsive?

My game is a 2D car-based one, with a straight infinite map where I've finally been able to add some random obstacles. There are only 3 positions the car can be at, and everything is working fine.
The point is that I've recently noticed that it is not responsive, and tried to make it responsive by adding a line like these one to the AppDelegate.cpp:
glview->setDesignResolutionSize(1024.0, 600.0, kResolutionFixedWidth);
I've tried to use kResolutionFixedWidth, kResolutionFixedHeight and all others 5 variables you can put there, but I only got black lines along the screen and every single screen breakdown you can imagine -.-'
I can figure out I need to resize my TMXTiledMap manually because of the nature of tiles (I did it with Tiled), but I don't know how to face this problem.
Note that I'm currently developing for a 1024x600 Android device but I would want to support at least the most common resolutions for both tablets and smartphones.
There are probably 2 resolution policies you want to use.
If you use No Border then you shouldn't see any black bars, but the engine will crop your design resolution so you won't want to put UI in the corners, or you'll want to use Visible Origin and Visible Size to calculate positions.
If you use Exact Fit you should set the design resolution to the devices exact size, and then you're responsible for positioning and scaling everything correctly to avoid distortion.
You will need to scale your art depending on your policy and design resolution choices if you are seeing black bars.
Have you read through this wiki page?
http://www.cocos2d-x.org/wiki/Multi_resolution_support
Here's what we do for one of our games:
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
float contentScaleFactor = 1.f;
// Set the design resolution
Size frameSize = glview->getFrameSize();
Size designSize = glview->getDesignResolutionSize();
CCLOG("defaults:");
CCLOG("framesize = {%f,%f}", frameSize.width, frameSize.height);
CCLOG("visibleSize = {%f,%f}", glview->getVisibleSize().width, glview->getVisibleSize().height);
CCLOG("designSize = {%f,%f}", designSize.width, designSize.height);
CCLOG("contentscalefactor = %f", director->getContentScaleFactor());
Vec2 origin = director->getVisibleOrigin();
CCLOG("visibleSize = %s", CStrFromSize(director->getVisibleSize()));
CCLOG("origin = {%f,%f}", origin.x, origin.y);
// Retina?
contentScaleFactor = director->getContentScaleFactor();
float designWidth = frameSize.width / contentScaleFactor;
float designHeight = frameSize.height / contentScaleFactor;
CCLOG("contentScale = %f, designWidth/Height = {%f,%f}", contentScaleFactor, designWidth, designHeight);
glview->setDesignResolutionSize(designWidth, designHeight, ResolutionPolicy::EXACT_FIT);
// we designed the game for 480x320 (hence the divisors)
// used to scale full screen backgrounds
float fullWidthScaleFactor = designWidth/480.f;
// used to scale up most UI
float largeScaleFactor = floorf(designHeight/320.f);
// round to closest HALF step (1.0,1.5,2.0,2.5,3.0,etc)
// used for scaling UI where pixel art is affected by .1 scales
float largeScaleFactorExact = floorf(designHeight * 2.f / 320.f) * 0.5f;
// used to scale up UI that must be touchable (larger on high desnsity)
float largeScaleFactorUI = STROUND(designHeight / 320.f);
// this forces minimum of 1x scale (we should just not support these devices)
float scaleFitAll = designWidth > designHeight ? designHeight/320.f : designWidth/480.f;
if(largeScaleFactor < 1.f)
largeScaleFactor = scaleFitAll;
if(largeScaleFactorExact < 1.f)
largeScaleFactorExact = scaleFitAll;
if(largeScaleFactorUI < 1.f)
largeScaleFactorUI = scaleFitAll;

Approximate indoor positioning using the integration of the linear acceleration

I am trying to calculate the approximate position of an Android phone in a room. I tried with different methods such as location (wich is terrible in indoors) and gyroscope+compass. I only need to know the approximate position after walking during 5-10seconds so I think the integration of linear acceleration could be enough. I know the error is terrible because of the propagation of the error but maybe it will work in my setup. I only need the approximate position to point a camera to the Android phone.
I coded the double integration but I am doing sth wrong. IF the phone is static on a table the position (x,y,z) always keep increasing. What is the problem?
static final float NS2S = 1.0f / 1000000000.0f;
float[] last_values = null;
float[] velocity = null;
float[] position = null;
float[] acceleration = null;
long last_timestamp = 0;
SensorManager mSensorManager;
Sensor mAccelerometer;
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_LINEAR_ACCELERATION)
return;
if(last_values != null){
float dt = (event.timestamp - last_timestamp) * NS2S;
acceleration[0]=(float) event.values[0] - (float) 0.0188;
acceleration[1]=(float) event.values[1] - (float) 0.00217;
acceleration[2]=(float) event.values[2] + (float) 0.01857;
for(int index = 0; index < 3;++index){
velocity[index] += (acceleration[index] + last_values[index])/2 * dt;
position[index] += velocity[index] * dt;
}
}
else{
last_values = new float[3];
acceleration = new float[3];
velocity = new float[3];
position = new float[3];
velocity[0] = velocity[1] = velocity[2] = 0f;
position[0] = position[1] = position[2] = 0f;
}
System.arraycopy(acceleration, 0, last_values, 0, 3);
last_timestamp = event.timestamp;
}
These are the positions I get when the phone is on the table (no motion). The (x,y,z) values are increasing but the phone is still.
And these are the positions after calculate the moving average for each axis and substract from each measurement. The phone is also still.
How to improve the code or another method to get the approximate position inside a room?
There are unavoidable measurement errors in the accelerometer. These are caused by tiny vibrations in the table, imperfections in the manufacturing, etc. etc. Accumulating these errors over time results in a Random Walk. This is why positioning systems can only use accelerometers as a positioning aid through some filter. They still require some form of dead reckoning such as GPS (which doesn't work well in doors).
There is a great deal of current research for indoor positioning systems. Some areas of research into systems that can take advantage of existing infrastructure are WiFi and LED lighting positioning. There is no obvious solution yet, but I'm sure we'll need a dedicated solution for accurate, reliable indoor positioning.
You said the position always keeps increasing. Do you mean the x, y, and z components only ever become positive, even after resetting several times? Or do you mean the position keeps drifting from zero?
If you output the raw acceleration measurements when the phone is still you should see the measurement errors. Put a bunch of these measurements in an Excel spreadsheet. Calculate the mean and the standard deviation. The mean should be zero for all axes. If not there is a bias that you can remove in your code with a simple averaging filter (calculate a running average and subtract that from each result). The standard deviation will show you how far you can expect to drift in each axis after N time steps as standard_deviation * sqrt(N). This should help you mathematically determine the expected accuracy as a function of time (or N time steps).
Brian is right, there are already deployed indoor positioning systems that work with infrastructure that you can easily find in (almost) any room.
One of the solutions that has proven to be most reliable is WiFi fingerprinting. I recommend you take a look at indoo.rs - www.indoo.rs - they are pioneers in the industry and have a pretty developed system already.
This may not be the most elegant or reliable solution, but in my case it serves the purpose.
Note In my case, I am grabbing a location before the user can even enter the activity that needs indoor positioning.. and I am only concerned with a rough estimate of how much they have moved around.
I have a sensor manager that is creating a rotation matrix based on the device orientation. (using Sensor.TYPE_ROTATION_VECTOR) That obviously doesn't give me movement forward, backward, or side to side, but instead only the device orientation. With that device orientation i have a good idea of the user's bearing in degrees (which way they are facing) and using the Sensor_Step_Detector available in KitKat 4.4, I make the assumption that a step is 1 meter in the direction the user is facing..
Again, I know this is not full proof or very accurate, but depending on your purpose this too might be a simple solution..
everytime a step is detected i basically call this function:
public void computeNewLocationByStep() {
Location newLocal = new Location("");
double vAngle = getBearingInDegrees(); // returns my users bearing
double vDistance = 1 / g.kEarthRadiusInMeters; //kEarthRadiusInMeters = 6353000;
vAngle = Math.toRadians(vAngle);
double vLat1 = Math.toRadians(_location.getLatitude());
double vLng1 = Math.toRadians(_location.getLongitude());
double vNewLat = Math.asin(Math.sin(vLat1) * Math.cos(vDistance) +
Math.cos(vLat1) * Math.sin(vDistance) * Math.cos(vAngle));
double vNewLng = vLng1 + Math.atan2(Math.sin(vAngle) * Math.sin(vDistance) * Math.cos(vLat1),
Math.cos(vDistance) - Math.sin(vLat1) * Math.sin(vNewLat));
newLocal.setLatitude(Math.toDegrees(vNewLat));
newLocal.setLongitude(Math.toDegrees(vNewLng));
stepCount =0;
_location = newLocal;
}

Moving object to touch x y

I'm trying to move an object to a new x,y position based on the user's touch location, but I've hit a brick wall.
Currently, I'm coding the movement of the axis manually, but it's producing a scripted, "x then y", resulting in a squared off movement. Ideally, I want to gain a linear path to the touch position, not a square.
My basic movement calculation is here:
//check target not met on x axis
if(spriteX != spriteTargetX){
//check if its left or right
if(spriteTargetX<spriteX){
spriteX -=spriteSpeed;
}else{
spriteX +=spriteSpeed;
}
}
if(spriteY != spriteTargetY){
//check if its up or down
if(spriteTargetY<spriteY){
spriteY -=spriteSpeed;
}else{
spriteY +=spriteSpeed;
}
}
The above algorithm always results in a square movement. I honestly don't know whether I should be performing some kind of distance/angle calculation. Any ideas?
One simple way to do this is to represent the direction of movement as a unit vector, and multiply by the speed. I'll list the basic steps, and give an example where you are at (1,1) and wish to move to (4,5) with speed 2:
Get difference between destination and current. (diff.x and diff.y)
diff.x = 3
diff.y = 4
Get the total distance from destination to current.
dist = 5 ( sqrt(3^2 + 4^2) = 5 )
Divide diff.x and diff.y by the distance
diff.x = 0.6
diff.y = 0.8
Multiply diff.x and diff.y by desired speed
diff.x = 1.2
diff.y = 1.6
Add diff.x and diff.y to sprite's x and y, respectively
sprite.x = 2.2
sprite.y = 2.6

Categories

Resources