I just wanted to know how I could get the speed that the UIAccelerometer is moving in so that I know how fast to move a UIView.
Oh boy this is a bit tricky.
The accelerometer does not give you Velocity, but as we all know this is acceleration. But you can figure it out (but its not that easy).
We need to use some simple physics calculations. Using
V(now) = V(previous) + acceleration(from accelerometer)*time(seconds since you last made a reading);
In code you would need to do a few things.
You must figure out when you are not moving. Eg leave device still for a second.
When the device moves you know the device started at an initial Velocity of 0m/s
Ok so lets pretend to make this real simple and we only check the accelerometer every 1 second (later on maybe do 10x a second.
Ok, we get the first reading of 1 second and the acceleration was 2.
So our velocity after 1 second from resting would be = 0 + 2*1 = 2 m/s
GREAT, now another second has passed (total time passed is 2 seconds), acceleration 2.5 velocity now would be
V(now) = Vpervious (2) + T(passed since previous reading) 1 * 2.5 = 2 + 1*2.5 = 4.5 m/s
Remember here that T here is time passed since last reading not total time.
If I am right (someone can correct me, the accelerometer is sending back the actual value of a in our equations). So you should be able to plug that in.
Also the accelerometer will be giving you 3 different values (x,y,z). So maybe first start with one direction then maybe y for another.
Would love to know if you got this working. John.
Related
I'm new to Unity and I see many times that Time.deltaTime needs to be added. In which cases should I add it? I know this is so that there will be no excess power in the event of a quick refresh of the frame's computer.
For example, in the next case, do I need to add Time.deltaTime?
playerRigidbody.AddForce(Vector3.up * 100 * Time.deltaTime, ForceMode.Impulse);
Time.deltaTime is the amount of seconds it took for the engine to process the previous frame. It's calculation is rather simple: it uses the system's internal clock to compare the system time when the engine started processing the previous frame to the system time when the engine started processing the current frame. Every motherboard has a "system clock" which is responsible to keep track of time. Operating systems have access to that system clock and provide API's to read that clock. And Unity gets the time from that API and that's how things are synchronized.
Think of a game as a movie, which is essentially a sequence of images. The difference is that a movie is rendered at a fixed rate of 24 images per second, while a game doesn't have a fixed frame rate.
In a movie, if a car travels at 1 meter per second, each image will make it move by 1/24 meter, and after 24 images (1 second) the car will have traveled exactly 1 meter. It's easy because we know that each frame takes exactly 1/24 second.
In a game, we have to do the same thing, except the frame rate varies. Some frames can take 1/60 second, some others can take 1/10 second. We can't use a fixed ratio. Instead of a fixed number we have to use Time.deltaTime. Each frame, the car will move a distance proportional to the time of the frame. After roughly 1 second, the car will have traveled roughly 1 meter
Delta is the mathematical symbol for a finite difference. Its use is very common in english when talking about something that changed over time.
deltaTime is a difference of time, so it's a Delta
Shorter Terms
You must always use Time.deltaTime when moving objects over time, either by supplying it yourself or by making use of functions like SmoothDamp that use Time.deltaTime by default (hardly any functions do that though). But you must never use Time.deltaTime for input that's already framerate-independent, such as mouse movement, since in that case using Time.deltaTime will do the opposite of what you intend.
If you're ever unsure you can always toggle vsync on and off and observe any potential speed differences. If the game's already running close to the monitor refresh rate anyway, then make use of Application.targetFrameRate instead.
In very easy words
Time.deltaTime is the time passed since last frame was rendered.
By multiplying a value with it you basically convert it from Something per frame into Something per second.
Is it needed?
Now if you need to use it totally depends on your specific use-case! In your case for AddForce: NO!.
The force influences the velocity of a physics object. The velocity itself already is an absolute per second vector.
Usually there are two use-cases for AddForce:
It is called continuously but within FixedUpdate
Because FixedUpdate is not called every frame anyway but rather on a fixed real time intervals (by default 0.02 seconds) you would not need Time.deltaTime. The Doc already provide this in the example.
It is anyway called only as a single event (e.g. by jumping)
Here there is nothing continuous, so you don't need and don't want to use Time.deltaTime either since a single event can not be frame-rate-dependent anyway.
I'm having a bit of a problem that I have been trying to figure out for the last ~5 days, basically, I want an object to move by a specific amount using AddForce, for example, lets say 1 unit, however, when I use this snippet of code
body.AddForce(new Vector3(1,0,0), ForceMode.Impulse);
instead of moving it by 1 unit, so that the position is
1,0,0
It moves it by
0.03291207,0,0
so I realized that there is a calculation here, so I thought maybe for every 1 velocity, it moves it by 0.0329...., so I figured if I were to multiply the velocity by around 30, however, if I put
body.AddForce(new Vector3(30,0,0), ForceMode.Impulse);
, but now it moves it by
37.92695,0,0
, so I was really confused. So after making a spreadsheet and then copying and pasting different velocities and how they work, I finally figured it out. so it works a something a bit like this :
basically, there are 3 things, the input value [which we will call X], the velocity, and the position. the Velocity starts outs as the X, and every frame its decreased by - 0.2355
the position starts out as whatever position it is, and then there is a speed value, lets call it Y, now Y starts out as X divided by 100 and multiplied by 2, so for example if X is 1, Y would start out as 0.02, then, ~0.0048 is removed from Y, so now it's 0.0152, and then every frame, the position is increased by the Y value, and also every frame, Y is being decreased by ~0.0048, ~0.0048 being the friction [I think].
and now that I knew how it worked, I could reverse engineer, and I did! so I figured out that to get the object to move by 1 unit, I needed to input around 5.02 velocity. So, you might be wondering if I figured it out, why am I posting it here? well, the problem arises when I try to move it on the Z-axis at the same time, like
body.AddForce(new Vector3(1,0,1), ForceMode.Impulse);
now it moves it by on both axis by
0.0500636, 0, 0.0500636
instead of
0.03291207,0,0.03291207
. So this really made me confused, so then I made a spreadsheet and then copied and pasted different velocities and how they work. And it turns out the formula is still the same, however, 0.2355 and 0.0048 are changed, for example when it's
body.AddForce(new Vector3(1,0,1), ForceMode.Impulse);
, 0.0048 is actually 0.00332966 so Y is being decreased by 0.00332966 every frame, but if there are 2 different numbers, then, they both have different 0.0048's, for example, if it's
body.AddForce(new Vector3(1,0,2), ForceMode.Impulse);
. for 1 the value is 0.00210584 meaning Y gets decreased by 0.00210584 every frame, but for 2 in the same vector, 0.00421168 is the magic number, meaning Y is decreased by 0.00421168 every frame.
And that's where I'm stuck, I can't figure out where these numbers are coming from. I tried dividing it, multiplying it, subtracting and adding and I just cant figure it out. So I would really appreciate help from the physics experts here. Keep in mind that I don't know that much about physics and only know a bit about algebra and stuff like that, so I have no idea what the correlations are. If anyone needs it, here is the table I made showcasing every "magic number" from 1 to 6, the colored squares are squares that are quite similar
Sorry if this post was a bit confusing and sorry if I'm not supposed to ask this here, but I'm not sure where else on stack could i ask this, this whole topic is a bit confusing so I'm not sure if I explained it well enough, and I'm a bit tired, so if you didn't understand anything just leave a comment and I will try to answer it, Thanks in advance for any help :)
I have a question about Lerp. So I know that lerp helps you to move your object like:
void update(){
transform.position = vector3.lerp(start.position,end.position, (Time.time / 1000));
}
this will get your object to your endposition.
But if you have this code:
void Update(){
transform.position = Vector3.Lerp(transform.position,
destination.position,
speed * 3.0f * Time.deltaTime);
}
How is it possible that your object arrives at your destination, the 3th parameter of lerp has to reaches slowly 1 so your objects arrives at your destination. But "speed" , "3.0" , "Time.deltaTime" will always be the same, so how is it possible that your object arrives at your destination?
So the big question: Is it possible to do the lerp with some variables, which have always the same value and with Time.deltaTime?
Now, because of the different comments etc. I don't know exactly how lerp works, i have to possibilities:
1.) First i thought it works like this:
Vector3.lerp(a,b,c)
The c value has to change every frame to move the object. If the c value is 0.2 your object will moved 20% of the way and if the c value doesn't change the object will always be on 20% of the way. So the get the object moved fluently your c value have to change every frame a little so you c value will go from 0 to 1 and so is your object going from start to destination.
Or is it like this
2.) Because of several comments i thought lerp works like this
Like the comments say, the c value doesn't have to change the value, becaue if you have c = 0.2 you will pass 20% of the way and the next frame, if c is still 0.2 you will pass 20% of the remaining way and so on.
So is it lerp working like 1(you have to change c) or is it working like 2(you don't have to change c)
The distance between your transform position and the destination is an exponential decay. The distance shrinks by (1 - speed) every frame (given that speed is less than 1). Say your game is supposed to run at 60FPS. If for whatever reason the frame rate drops to 30FPS, the deltaTime is gonna be twice as big and you’re supposed to execute the Lerp 2 times. In such case, the distance will shrink by (1 - speed) then (1 - speed) again yielding a result of (1 - speed)^2 shrinkage. From this, you can generalize that the shrink amount of the distance is (1 - speed) ^ (deltaTime / baseDeltaTime) with baseDeltaTime being the deltaTime the game is supposed to run at i.e. 1/60 (for 60FPS).
To put in code:
transform.position = Vector3.Lerp(transform.position, destination.position, 1 - Mathf.Pow(1 - speed * 3.0f, Time.deltaTime * 60));
The object reaches the goal because your start position is the current position, and after lerping, you set the position of the object to the resulting position of Lerp. If you change your starting position to a normal Vector3 it would Lerp to "speed * Time.deltaTime * 3f"
I guess you didn't understand that how lerp works in unity. I will recommend you this Article of Robbert How to Lerp like a pro.
I see this sort of thing far too often:
transform.position = Vector3.Lerp(startPos, endPos, Time.deltaTime);
The person posting it is usually convinced that Vector3.Lerp is
“broken”, but the real problem is that they’re not using it correctly.
Lerp, short for “linear interpolation” does one very simple thing:
given two values, x and y, it returns a value that is t percent
between them. If you expect the output to change, the arguments you
pass in need to reflect that!
In the example above, it doesn’t make sense to just pass in
Time.deltaTime, because that’s only the time that passed during the
most recent frame. If your game is running at a constant 50fps, that’s
always going to be 0.02.
myLocation = Mathf.Lerp(myLocation, myDestination, 0.02)
If you are storing the return of the Lerp function into a variable and then also using that same variable as the minimum value in that same Lerp function, then the min value is getting bigger and bigger everytime the function is called.
So, even though you're not changing T, you're changing the starting value and thus, the stored value gets closer and closer to the max value.
It will accelerate very quickly initially and then slow down the closer it gets to the max value. Also, the max value will either never be reached or take an extremely long time.
(See https://gamedev.stackexchange.com/questions/149103/why-use-time-deltatime-in-lerping-functions)
There are two common ways to use Lerp:
1. Linear blending between a start and an end
progress = Mathf.Clamp01(progress + speedPerTick);
current = Mathf.Lerp(start, end, progress);
2. Exponential ease toward a target
current = Mathf.Lerp(current, target, sharpnessPerTick);
Note that in this version the current value appears as both the output and an input. It displaces the start variable, so we're always starting from wherever we moved to on the last update. This is what gives this version of Lerp a memory from one frame to the next. From this moving starting point, we then then move a fraction of the distance toward the target dictated by a sharpness parameter.
This parameter isn't quite a "speed" anymore, because we approach the target in a Zeno-like fashion. If sharpnessPerTick were 0.5, then on the first update we'd move halfway to our goal. Then on the next update we'd move half the remaining distance (so a quarter of our initial distance). Then on the next we'd move half again...
This gives an "exponential ease-out" where the movement is fast when far from the target and gradually slows down as it approaches asymptotically (though with infinite-precision numbers it will never reach it in any finite number of updates - for our purposes it gets close enough). It's great for chasing a moving target value, or smoothing a noisy input using an "exponential moving average," usually using a very small sharpnessPerTick parameter like 0.1 or smaller.
In my current project I ran into trouble regarding the quaternion provided by Core Motion's CMAttitude. I put the iPhone 5 (iOS 6.0.1) at a well defined start position. Then I start to move the device quickly around like in a fast pacing game. When I return to the start position after 10-30 seconds the reported yaw angle differ from the start position for 10-20 degrees (most of the time ≈11°).
I used the old (and sadly no longer available) Core Motion Teapot sample to validate the effect. The Euler Angles for logging are read directly from CMAttitude:
NSLog(#"pitch: %f, roll: %f, yaw: %f", attitude.pitch * 180 / M_PI, attitude.roll * 180 / M_PI, attitude.yaw * 180 / M_PI);
I found this on two different iPhone 5 devices manufactured at different times in different factories. But really weird is that my iPhone 4, running iOS 5.1.1, is working as expected. It seems to me an iOS bug and I filed a bug report already, but on the other hand I can hardly imagine that nobody had yet stumbled upon it. I suspect it might has to do with the redesigned Core Motion API. Starting with version 5 the magnetometer (compass) is considered for sensor fusion as well. Console shows that bias estimations from locationd are provided to CoreMotion:
locationd[41] <Notice>: GYTT inserted: bias,-0.196419,1.749323,-1.828088,variance,0.002644,0.004651,0.002527,temperature,31.554688
My question(s): Is there chance to block magnetometer readings when using Device Motion? I tried deactivating location services but it doesn't affect Core Motion. If not possible, what is the alternative / workaround, Accelerometer based gravity estimation?
PS: As we are dealing with quaternion based models this is not related to Gimbal Lock
EDIT:
After doing some more measurements it seems clear that only yaw is affected. Pitch and roll show deviations within tolerance (<= 1°) while yaw is drifting regardless of the starting position. CMDeviceMotion.gravity appears to be clean too.
EDIT (2):
I could reproduce the problem with the MotionGraphs sample attached to recent XCode versions. The yaw graph is reproducibly drifting away from origin.
Not the definitive solution but at least a workaround for my own question (I leave it as unanswered to invite you). It turned out that at least DeviceMotion.gravity is not affected by the bug. So I decided to redesign this pretty simple part of motion detection and use arcsin (gravity.x/||gravity||) for moving the main player character to the side when tilting the device.
This is definitely the second best solution as it destroys information about the full rotation status contained in a quaternion. I decided to it that way for strategical considerations:
I think most developers do tilt motion detection with the gravity vector rather than CMAttitude.quaternion because most people are not that amused about quaternion maths ;-) Thus any future bugs related to the gravity vector will probably be fixed during the beta phase because of a larger number of users.
If it is a software bug and not related to hardware issues, what I assume, and if the bug will be fixed ASAP, there is still a number of devices that might not get updated for what reason ever. Thus the risk that a potential future customer will run into trouble is small but > 0. So the second best solution might be sometimes the best.
I've done something similar in my own code and found the same z-axis rotational drift (yaw). I've applied a balanced filter. At each motion manager time interval, I grab the current quaternion (z-component) and then save that after calculations as oldZ, for use in the next set of calculations. My filter simply balances the NEW z value with the z value immediately preceeding it, preventing it from moving too much too quickly. Depending on your hardware and the exact tolerance in your program, you can manage drift quite well in this way. You will see the gyro drift slightly, but then begin to be corrected as the filter continues to act. My filter looks something like this and prevents more than 0.5 degree of "stray":
filtZ = 0.65 * oldZ + 0.35 * z;
The 0.65 and 0.35 values were determined experimentally and I would advise you to play with those as you have time. Output will still be scaled 0-1 and can then be utilized in the same way you've been doing (or re-introduced to the quaternion if you must retain all 4 dimensions throughoutf).
I've been experimenting with the compass and gyroscope on iPhone 4 and would like some help with an issue I'm having. I want to compensate for the slowness of the compass by using data from the gyroscope.
Using CMMotionManager and its CMDeviceMotion object (motionManager.deviceMotion), I get the CMAttitude object. Correct me if I'm wrong (please), but here is what I've deduced from the CMAttitude object's yaw property (I don't need pitch nor roll for my purposes):
yaw ranges from 0 to PI when the phone is pointing downwards (as indicated by deviceMotion.gravity.z) and swinging counterclockwise and 0 to -PI when swung clockwise
when the device is pointing upwards, yaw ranges from -PI to 0 and PI to 0, respectively
and from the compass data (I'm using locationManager.heading.magneticHeading), I see that the compass gives values from 0 to 360, with the value increasing when swinging clockwise
All right, so using all of this information together, I'm able to get a value I call horizontal that, regardless of whether the device is pointing up or down, will give values from 0 to 360 and increase when the device is swung clockwise (though I am still having trouble when deviceManager.gravity.z is around 0 -- the yaw value freaks out at this gravity.z value).
It seems to me that I could "synchronize" the horizontal and magneticHeading values, using a calculated horizontal value that maps to magneticHeading, and "synchronize" the horizontal value to magneticHeading when I feel the compass has "caught up."
So my questions:
Am I on the right track with this?
Am I using the gyro data from CMDeviceMotion properly and the assumptions I listed above correct?
Why might yaw freak out when gravity.z is around 0?
Thank you very much. I look forward to hearing your answers!
Just trying to answer... correct me if i'm wrong..
1.Yes you are on the right track
2.gravity in CM is already "isolated" from user gravity (gravity value caused by user acceleration) thats why there is two gravity, the "gravity" and "userAcceleration" its on apple CM documentation
// Note : not entirely isolated //
3.
if you have a gravity 0 it mean that the coresponding axis is perpendicular with gravity.
gravity.z is the iPhone screen thats why it -9.82m/s2 if you put on the desk with screen upright, actualy it hard to get 0 or maximum value of the gravity due to the sensor noise (it's normal, all sensor has a noise expecially cheap sensor).
what i do on my apps is I will switch my reference axis to other axis (in your case may be x or y) for certain limits, how the strategy is depend on the purpose or which side is your reference.
the other thing is, gyro is fast but its not stable, you need to re-calibrate the value for several interval. In my case every 5 second. I've experiment with gyro for calculating angle between two plane, i try with exacly 90 degree ruler and it will give an error about 0.5 degree every second try and keep increasing, but thats is mine, maybe others have a better method for avoid the error.
below is my steps "
Init
Read gravity XYZ -> Xg Yg Zg
Check if Xg < 0.25 If TRUE try Yg then Zg // Note 1 = 1g = 9.82 m/s^2
Read the compass and gyro
Configure and calibrate the gyro using the compass and calulate based on which axis i use in point 3.
If 5 second is pass then recalibrate, read the compass
If the the difference with gyro reading is > 5 degree skip recalibartion the gyro.
If the the difference with gyro reading is < 5 degree calibrate the gyro using compass value
Note: for number 7 : is to check if the phone affected with magnetic field or near huge steel such or high voltage electrical line or in noisy and heavy equipment in factory plant.
Thats all... Hope this could help you...
And sorry for my english..
Here is an example of an iPhone app where the compass get compensated with the gyroscope. Code and project can be seen here:
http://www.sundh.com/blog/2011/09/stabalize-compass-of-iphone-with-gyroscope/
The direction of the yaw axis vector is undefined when in zero gravity (or free fall, or close enough).
In order to do synchronization while in motion, you need to create a filter for your "horizontal" value that has the same lag/delay response characteristics as the magnetic compass. Either that, or wait until motion stops long enough for both values to settle before recalculating the offset.
Answer to question 1 is Yes, question 2 you are on the right track but you could use a variable name that is not 'horizontal', question 3 is answered by hotpaw2 and also a yaw in a chopper or helicopter at near zero altitude would alert the pilot with an alarm. There is a time lag because part of the software is local while there are other factors which can slow it down including access to a sensor for detecting magnetic waves, the device position and direction, preparing the graphic output for the compass display, computing and outputting data from the gyro and sensors through a relatively slow interface, using a general purpose handheld device not custom designed for the type of task being asked of it.