Unity3D BezierCurve - Spline Walker Following AI? - unity3d

I've been struggling to create a game with a competent (but fair) racing AI, and I have several constraints that I'm trying to meet. Here's the conditions in order:
1.) The AI logic and player controls BOTH share the same car controller to drive and turn, etc. The AI vehicle simply passes a clamped (-1 to 1) value depending on how far the car is trying to turn and the throttle is engaged. Both the AI and player share the boolean to brake, and drift turning with the SHIFT key
2.) The AI needs to make smart, informed decisions that the player would in applying the right amount of turn, when to coast, etc.
I originally used a plain waypoint increment system to have the AI continue lapping around the track depending on the waypoints. With the right wheel friction curve values (which I happened to luckily find online) this actually works OK. However, while I was struggling more with the wheel friction values especially, and still want to have a smoother path following and turning logic for the AI, it was suggested to me to use cubic Bezier splines. I found the Catlike Coding tutorial fascinating (I'm sure many of you know this, but here's the link below for anyone interested):
https://catlikecoding.com/unity/tutorials/curves-and-splines/
I then got the idea of using the Spline Walker from this tutorial to be the ONE waypoint for the AI, and effectively "tease" the car to follow the spline walker, like this video:
https://www.youtube.com/watch?v=UcA4K2rmX-U#action=share
However, here's my big problem - if I want to have my car FOLLOW the spline walker, while keeping the spline walker always in front, I have to ensure the "progress" that the spline walker follows is relative to the position of the following car, with the spline walker remaining a LITTLE in front so that the car doesn't decide to slow down and stop.
I've been looking for examples to do this, and I can't say I've been too successful.
Here's my current progress calculating code snippets - I'm trying to store distances between positions on the spline right now, via the old waypoint objects which happen to share the same transform coordinates:
private void Start()
{
Rigidbody rb = chasingCar.GetComponent<Rigidbody>();
if(path)
{
nodes = path.GetComponentsInChildren<Transform>();
}
Array.Resize(ref distances, nodes.Length-1);
for (int i = 0; i < nodes.Length-1; i++)
{
//start storing the distances between two successive waypoints on the spline
distances[i] = Vector3.Distance(nodes[i].position, nodes[i + 1].position);
totalDistance += distances[i];
}
Debug.Log("First distance value is " + distances[0] + " and overall distance est is " + totalDistance);
Debug.Log("Second distance value is " + distances[1] + " and overall distance est is " + totalDistance);
Debug.Log("Fifth distance value is " + distances[4] + " and overall distance est is " + totalDistance);
}
This is in the update function for the spline walker when the chasing car and it's old waypoint path have been provided to the spline:
Vector3 position;
if (chasingCar && path)
{
float distFromCar = Vector3.Distance(transform.position, chasingCar.transform.position);
Debug.Log("Distance from car " + distFromCar);
if(distFromCar < 35)
{
//get current spline waypoint
//int splineIdx = GetSplineIndex(progress);
int splineIdx = chasingCar.GetComponent<CarEngine>().GetCurrentNodeTarget();
//declare next spline waypoint
int splineIdxNext = splineIdx + 1;
if (path && splineIdxNext == (nodes.Length))
splineIdxNext = 0;
Debug.Log("Current splineIdx " + splineIdx);
//float currCarDistance = Vector3.Distance(chasingCar.transform.position, nodes[splineIdx].position);
float currCarDistance = SumSplineProgress(splineIdx);
float overallDistance = Vector3.Distance(nodes[splineIdx].position, nodes[splineIdxNext].position);
float currCarSplineProgress = currCarDistance / overallDistance;
float overallProgress = (currCarDistance) / (totalDistance);
progress = overallProgress;
}
else
{
progress += Time.deltaTime / duration;
}
Debug.Log("Chasing, current progress: " + progress);
position = spline.GetPoint(progress);
Finally, here's the functions I've tried to use to calculate the spline walker progress in the past:
int GetSplineIndex(float progress)
{
float curProgress = progress * (totalDistance);
Debug.Log("Current calculated progress " + curProgress);
return System.Convert.ToInt32(Mathf.Floor(curProgress));
}
float SumSplineProgress(int index)
{
float currTotalDistance = 0f;
for(int i = index; i > -1; i--)
{
currTotalDistance += distances[i];
}
return currTotalDistance;
}
I might just be making it harder on myself than I need to, but I'm just going to say, I'm legit stumped. I got close with having the spline waypoint jump ahead of the car MORE when there is more distance between the current start and end waypoint for the AI car, but that's still not what I'm trying to achieve.
Anyone have any particular suggestions here? Tips, nudges in the direction, and code would be fantastic. Thanks in advance!
UPDATE
Yes, I'm still working on this! There was some logic that I regarded as faulty in the previous spline calculation code - for instance, this:
float currCarSplineProgress = currCarDistance / overallDistance;
I've changed to this:
float currCarSplineProgress = (currCarDistance) / currSplineLength;
The idea of that part is to check the car's progress on the current curve it is traveling close to in the overall spline, and position the spline walker accordingly so that it jumps ahead to the next spline when needed. Here's the full updated code:
Vector3 position;
if (chasingCar && path)
{
float distFromCar = Vector3.Distance(transform.position, chasingCar.transform.position);
Debug.Log("Distance from car " + distFromCar);
if(distFromCar < 50)
{
//get current spline waypoint
//int splineIdx = GetSplineIndex(progress);
int splineIdx = chasingCar.GetComponent<CarEngine>().GetCurrentNodeTarget()-1;
//declare next spline waypoint
int splineIdxNext = splineIdx + 1;
if(splineIdx == -1)
{
splineIdx = nodes.Length - 2;
splineIdxNext = 0;
}
if (path && splineIdxNext == (nodes.Length))
splineIdxNext = 0;
Debug.Log("Current splineIdx " + splineIdx);
//float currCarDistance = GetConvertedDistance(chasingCar.transform.position, nodes[splineIdx].position);
float currCarDistance = Vector3.Distance(chasingCar.transform.position, nodes[splineIdx].position);
float restDistance = Vector3.Distance(chasingCar.transform.position, nodes[splineIdxNext].position);
//float currCarDistance = SumSplineProgress(splineIdx);
Debug.Log("currCarDistance " + currCarDistance);
//float currSplineLength = Vector3.Distance(nodes[splineIdx].position, nodes[splineIdxNext].position);
float currSplineLength = currCarDistance + restDistance;
float overallDistance = 0;
float nextOverallDist = 0f;
if(splineIdx != 0)
overallDistance = SumSplineProgress(splineIdx-1);
Debug.Log("overallDistance " + overallDistance);
float currCarSplineProgNext = 0f;
if (splineIdxNext != 1 && splineIdxNext != 0)
{
nextOverallDist = SumSplineProgress(splineIdxNext - 1);
currCarSplineProgNext = (currCarDistance) / nextOverallDist;
}
Debug.Log("currSplineLength " + currSplineLength);
float currCarSplineProgress = (currCarDistance) / currSplineLength;
float leading = 10f;
if (distFromCar < 20)
leading += 15f;
float overallProgress;
Debug.Log("currCarSplineProgress " + currCarSplineProgress);
if (currCarSplineProgress < .7f)
{
overallProgress = (currSplineLength + (currCarDistance * .3f)) / (totalDistance);
}
else
{
Debug.Log("Jumping to next waypoint...");
overallProgress = (nextOverallDist + (currCarDistance * .3f)) / (totalDistance);
}
Debug.Log("Overall progress " + overallProgress);
//if (overallProgress >= 1f)
// overallProgress = 0f;
progress = overallProgress;
}
else
{
progress += Time.deltaTime / duration;
}
Debug.Log("Chasing, current progress: " + progress);
position = spline.GetPoint(progress);
}
else
{
position = spline.GetPoint(progress);
}
transform.localPosition = position;
Yet, unexpected things STILL happen when the car makes enough progress - the spline walker will just suddenly jump to one of the previous sections!
Any insights?

You have the right idea for making the AI chase a target moving along the spline. I believe that's how most AI in racing games work.
To ensure the target is always ahead of the AI, set the target's position to the AI's position on the spline added by some value related to how fast the AI is moving.
I would suggest checking out the Unity Standard Assets package:
https://assetstore.unity.com/packages/essentials/asset-packs/standard-assets-for-unity-2017-3-32351
There is a car AI system in there that works by following a target that is moving along a spline.

Related

Physics.Raycast doesnt seem to work consistently

I'm working on a raycast based pathfinding system. Basically what I'm trying to do is generate points around an object/check if that object can reach those points, and check if those points can reach the target. The target is the green cylinder in the back of the photo. Here is my layer mask which basically says to ignore the player as a collider/obstacle:
layerMask = Physics.DefaultRaycastLayers & ~(1 << 3);
Here is my raycasting code:
// Check if enemy can see player without any obstructions
bool CanSeeDestination(Vector3 startingPoint, Vector3 destination)
{
if(Physics.Raycast(startingPoint, destination, 50f, layerMask))
{
Debug.DrawLine(startingPoint, destination, Color.red);
return false;
} else
{
Debug.DrawLine(startingPoint, destination, Color.green);
return true;
}
}
And finally my pathfinding function:
// Raycast based pathfinding
void Pathfind()
{
List<Vector3> surroundingPoints = new List<Vector3>();
bool foundTarget = false;
// Nested loop to build surrounding points vector array
for(var i = 1; i <= 10; i++)
{
for(var k = 1; k <= 10; k++)
{
// Offset by half of max to get negative distance
int offsetI = i - 5;
int offsetK = k - 5;
surroundingPoints.Add(new Vector3(transform.localPosition.x + offsetI, stepOverHeight.y, transform.localPosition.z + offsetK));
}
}
// Loop through array of surrounding vectors
for(var m = 0; m < surroundingPoints.Count; m++)
{
// If enemy can reach this surrounding point and this surrounding point has an unobstructed path to the target
if(CanSeeDestination(transform.localPosition, surroundingPoints[m]) && CanSeeDestination(surroundingPoints[m], player.transform.position))
{
float distanceFromEnemyToTarget = Vector3.Distance(transform.position, surroundingPoints[m]);
float distanceFromTargetToPlayer = Vector3.Distance(surroundingPoints[m], player.transform.position);
float totalDistance = distanceFromEnemyToTarget + distanceFromTargetToPlayer;
// If this total path distance is shorter than current path distance set this as target
if(totalDistance < currentPathDistance)
{
currentPathDistance = totalDistance;
target = surroundingPoints[m];
foundTarget = true;
}
}
}
if (!foundTarget)
{
target = transform.position;
}
}
For some reason the raycasts trigger on the right side of the obstacle but not the left. Also if I increase the obstacle size or collider size I can eventually block the left side. Not sure why raycasts on the left are green and still passing through the collider.
I resolved the issue. The problem was in this line:
if(Physics.Raycast(startingPoint, destination, 50f, layerMask))
I should have been using Physics.Linecast two go between two points. Raycast goes in a vector "Direction" linecast goes between two points. The correct code is:
if(Physics.Linecast(startingPoint, destination, layerMask))

find the heading angle between 2 objects taking into account the forward angle of the initial object

Ok, so, i've been stuck on this for ages. Im working on an AI that will navigate a tank to a waypoint, defined as a Vector3. the position of the tank is also defines as a Vector3, both these have their Y position set to 0, as to ignore terrain elevation, the current rotation of the tank is also a Vector3, though only the Y rotation is needed, as i'm effectively projecting the 3d position onto a 2d navigational grid.
The AI passes anywhere between -1 and 1 into the control for the tank, which then handles the physics operations. so, i need to somehow calculate the angle, positive or negative in relation to the current heading angle of the tank to the position of the waypoint, then send the rotation value to the controls. At the moment I simply cant get it working, I feel like iv'e pretty much tried everything.
This is my code currently, it doesn't work, at all, and is about the 20th revision:
void driveToTarget()
{
Vector3 target0 = driveTarget;
target0.y = 0;
GameObject current0Obj = new GameObject();
Vector3 current0 = this.transform.position;
current0.y = 0;
print(current0);
print(target0);
Vector3 current0Angle = this.transform.eulerAngles;
print(current0Angle.y);
current0Angle.x = 0;
current0Angle.z = 0;
Vector3 heading = target0 - current0;
Quaternion headingAngle = Quaternion.LookRotation(heading);
print("headingAngle" + headingAngle);
print("heading direction, allegidly: " + Quaternion.Euler(heading).ToEulerAngles());
Quaternion distanceToGo = Quaternion.Lerp(Quaternion.Euler(current0Angle), headingAngle, 0.01f);
float angle = Vector3.SignedAngle(current0, target0, Vector3.up);
float difference = Mathf.Abs(angle - current0Angle.y);
print("heading angle " + angle);
if (current0 != driveTarget)
{
steeringVal = Mathf.Abs(1.5f-(1f/Mathf.Abs(distanceToGo.y))) * -Mathf.Sign(distanceToGo.y); ;
throttleVal = 0f;
} else
{
throttleVal = 0;
}
}
--EDIT--
So, I've partially solved it, and now encountered another problem, I've managded to get the tank to detect the angle between itself and the waypoint, BUT, rather than orienting forward towards the waypoint, the right side of the tank orients towards it, so it orbits the waypoint. I actually know why this is, becasue the forward vector of the tank is technically the right vector because of unity's stupid axis ruining my blender import, anyway, heres the updated code:
void driveToTarget()
{
Vector3 target0 = driveTarget;
target0.y = 0;
Vector3 current0 = this.transform.position;
current0.y = 0;
print("Current: " + current0);
print("Target: " + target0);
Vector3 current0Angle = this.transform.rotation.eulerAngles;
print("Curret rotation:" + current0Angle.y);
current0Angle.x = 0;
current0Angle.z = 0;
Vector3 heading = target0 - current0;
Quaternion headingAngle = Quaternion.LookRotation(heading);
print("heading angle: " + headingAngle.ToEuler());
float distanceToGo = (current0Angle.y) - headingAngle.eulerAngles.y;
print("DistanceToGo: " + distanceToGo);
if (current0 != driveTarget)
{
steeringVal = 1 * -Mathf.Sign(distanceToGo);
throttleVal = 0f;
} else
{
throttleVal = 0;
}
Debug.DrawRay(current0, heading, Color.red, 1);
Debug.DrawRay(current0, this.transform.up, Color.red, 1);
}
I'm not sure exactly how your code is setup or how the steering works. You may want to look into using the Unity NavMeshAgent to simplify this.
Regardless here is some code I wrote up that takes a destination and rotates an object towards it. All you'd have to do from there is move the object forwards.
Vector3 nextDestination = //destination;
Vector3 direction = nextDestination - transform.position;
direction = new Vector3(direction.x, 0, direction.z);
var newRotation = Quaternion.LookRotation(direction);
var finalRotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime); //smoothes out rotation
transform.rotation = finalRotation;
Sorry if this isn't what you needed. Have you been able to figure out which part of the code is behaving unexpectedly from your print statements?

Unity 2D Launch object twards mouse at consistent speed regardless of distance to object

I have an object that I would like to be 'launched' at the mouse position, but depending on the distance of the mouse to the object, the speed will change.
I need a consistent launch speed regardless of distance.
_destination is the mouse position
public void GoToDestination(Vector3 _destination)
{
//Vector3 rotation = Vector3.
//Debug.Log(" :" + _destination.x + " " + _destination.y);
//Debug.Log("Norm:" + _destination.normalized.x + " " + _destination.normalized.y);
//Vector3 diff = _destination - transform.position;
//Vector3 flippedDest = new Vector3(diff.x, diff.y, 0);
//rb.AddForce(flippedDest * speed);
//Debug.Log(rb.velocity);
//_destination.y = -_destination.y;
//_destination = (_destination - transform.position).normalized;
//rb.velocity = Vector3.Cross(transform.position, _destination) * speed;//(_destination.normalized - transform.position.normalized) * speed;
//rb.AddForce(_destination * speed);
//destination = _destination;
rb.velocity = (_destination - transform.position).normalized * (speed);
//destination = _destination;
}
If I understand you correctly you want to use distance as a variable for your speed calculation.
I assume this script run on a launched object.
First thing:
//distance between launched object(transform.position) and mouse position(destination).
float dist = Vector3.Distance(transform.position, destination.position);
You can calculate distance on every frame or whatever you want
Then:
You have dist variable as a float now . For example if you want to slowdown object when distance become smaller, you can simply multiply with dist like that.
The solution was to convert all Vector3's to Vector2's. The z axis was causing problems.

AnimationCurve.Evaluate - Get time by value

Is there a build-in way how to get a time by value from Animation curve in Unity3d? (The opposite way of Evaluate)
I need to achieve this (instead of getting value from time):
float time = AnimationCurve.Evaluate(float value);
Generically speaking getting X value from Y value.
I know this is 3 years old, but I found via a Google search, and in case someone else lands here:
I simply create an inverse curve, which allows me to look up by time.
public AnimationCurve speedCurve;
private AnimationCurve inverseSpeedCurve;
private void Start()
{
//create inverse speedcurve
inverseSpeedCurve = new AnimationCurve();
for (int i = 0; i < speedCurve.length; i++)
{
Keyframe inverseKey = new Keyframe(speedCurve.keys[i].value, speedCurve.keys[i].time);
inverseSpeedCurve.AddKey(inverseKey);
}
}
Just a basic implementation maybe it will give an idea for you. Method loops through all time and if your value is near that value at that time it will yield. It's a coroutine but you can change it to use inside Update maybe?
public AnimationCurve curve;
public float valToTime = .5f;
public float treshold = .005f;
public float yourTime;
IEnumerator valueToTime(float determineTime)
{
float timeCounter = 0;
Keyframe[] k = curve.keys;
float endTime = k[k.Length-1].time;
Debug.Log("end "+endTime);
while(timeCounter < endTime)
{
float val = curve.Evaluate(timeCounter);
Debug.Log("val "+ val + " time "+timeCounter);
// have to find a better solution for treshold sometimes it misses(use Update?)!
if(Mathf.Abs(val - determineTime) < treshold)
{
//Your time would be this
yourTime = timeCounter;
yield break;
}
else
{
//If it's -1 than a problem occured, try changing treshold
yourTime = -1f;
}
timeCounter += Time.deltaTime;
yield return null;
}
}
Putting together the best elements of most of the solutions posted, I've come up with an approach that produces pretty high accuracy. It involves doing the work upfront and so, is also quite efficient.
Note: If the original curve possesses any maximum/minimum point (points on the curve with a gradient of zero) this method will still attempt to invert it but can only do so by introducing several discontinuities to the inverted curve. It is not ideal for such cases.
Evaluate the original curve at several "sample-points" using a "sample-delta" constant.
For each "value" evaluated, compute the tangent at that point as the "sample-delta" / "value-delta".
Create keyframes that use the "value" as the "time" and the "sample-point" as the "value", and set the "inTangent" and "outTangent" to the tangent obtained in Step 3.
Add the keyframe generated at every "sample-point" to a new AnimationCurve().
The new AnimationCurve() is therefore an inverted version of the original.
Smooth the tangents of the new AnimationCurve() (the inverted version) to remove discontinuities caused by sudden and rapid tangent changes. NB: Smoothing the tangents may make the inverted curve lose it's general definition if the original curve had at least one maximum/minimum point.
Image of Normal Curve vs Inverted Curve:
invertedCurve = new AnimationCurve();
float totalTime = normalCurve.keys[normalCurve.length - 1].time;
float sampleX = 0; //The "sample-point"
float deltaX = 0.01f; //The "sample-delta"
float lastY = normalCurve.Evaluate(sampleX);
while (sampleX < totalTime)
{
float y = normalCurve.Evaluate(sampleX); //The "value"
float deltaY = y - lastY; //The "value-delta"
float tangent = deltaX / deltaY;
Keyframe invertedKey = new Keyframe(y, sampleX, tangent, tangent);
invertedCurve.AddKey(invertedKey);
sampleX += deltaX;
lastY = y;
}
for(int i = 0; i < invertedCurve.length; i++)
{
invertedCurve.SmoothTangents(i, 0.1f);
}
I needed this very thing just now, so I came up with this. I found it quite accurate and fast (an accuracy value of 10 was enough, and even lower may have done). But it will only work on curves that have ONE definite time for each value (i.e. nothing like waves with multiple times having the same value).
Similar to the other answer, it iterates through possible times - but rather than in a linear fashion the step value starts as the entire time range and halves each time.
Hope it's useful for you.
// NB. Will only work for curves with one definite time for each value
public float GetCurveTimeForValue( AnimationCurve curveToCheck, float value, int accuracy ) {
float startTime = curveToCheck.keys [0].time;
float endTime = curveToCheck.keys [curveToCheck.length - 1].time;
float nearestTime = startTime;
float step = endTime - startTime;
for (int i = 0; i < accuracy; i++) {
float valueAtNearestTime = curveToCheck.Evaluate (nearestTime);
float distanceToValueAtNearestTime = Mathf.Abs (value - valueAtNearestTime);
float timeToCompare = nearestTime + step;
float valueAtTimeToCompare = curveToCheck.Evaluate (timeToCompare);
float distanceToValueAtTimeToCompare = Mathf.Abs (value - valueAtTimeToCompare);
if (distanceToValueAtTimeToCompare < distanceToValueAtNearestTime) {
nearestTime = timeToCompare;
valueAtNearestTime = valueAtTimeToCompare;
}
step = Mathf.Abs(step * 0.5f) * Mathf.Sign(value-valueAtNearestTime);
}
return nearestTime;
}
just stumbled upon this problem myself and didn't like the solutions mentioned here, so i wanted to share my own. It's rather an adaption to the answer which inverts the keyframes.
I improved it by also inverting the tangents and the weight of the points.
I'm sure there is an easier way, but i found this working nicely for reversing the animationcurve.
Edit: Forgot to mention, for me it only worked when the tangents are set to weighted, i don't know what weight calculation unity does when you set it to auto or similar, so weighted was predicatable and easy to inverse.
inverseCurve = new AnimationCurve();
for (int i = 0; i < initialCurve.length; i++)
{
float inWeight = (initialCurve.keys[i].inTangent * initialCurve.keys[i].inWeight) / 1;
float outWeight = (initialCurve.keys[i].outTangent * initialCurve.keys[i].outWeight) / 1;
Keyframe inverseKey = new Keyframe(initialCurve.keys[i].value, initialCurve.keys[i].time, 1/initialCurve.keys[i].inTangent, 1/initialCurve.keys[i].outTangent, inWeight, outWeight);
inverseCurve.AddKey(inverseKey);
}
Thought I'd share my own version, as suggested in other forums too I tried looping over Evaluate() instead of reversing the whole curve which I think is overkill and not always feasible.
This checks for a value approximation down to the indicated decimals, it also assumes that the curve has "normalized" time (if it wasn't the case this could be expanded by looking for the smallest and the biggest time keys.
/// <summary>
/// Inverse of Evaluate()
/// </summary>
/// <param name="curve">normalized AnimationCurve (time goes from 0 to 1)</param>
/// <param name="value">value to search</param>
/// <returns>time at which we have the closest value not exceeding it</returns>
public static float EvaluateTime(this AnimationCurve curve, float value, int decimals = 6) {
// Retrieve the closest decimal and then go down
float time = 0.1f;
float step = 0.1f;
float evaluate = curve.Evaluate(time);
while(decimals > 0) {
// Loop until we pass our value
while(evaluate < value) {
time += step;
evaluate = curve.Evaluate(time);
}
// Go one step back and increase precision of the step by one decimal
time -= step;
evaluate = curve.Evaluate(time);
step /= 10f;
decimals--;
}
return time;
}

How can I find distance traveled with a gyroscope and accelerometer?

I want to build an app that calculates accurate Distance travelled by iPhone (not long distance) using Gyro+Accelerometer. No need for GPS here.
How should I approach this problem?
Basic calculus behind this problem is in the expression
(and similar expressions for displacements in y and z) and basic geometry is the Pythagorean theorem
So, once you have your accelerometer signals passed through a low-pass filter and binned in time with sampling interval dt, you can find the displacement in x as (pardon my C...)
float dx=0.0f;
float vx=0.0f;
for (int i=1; i<n; i++)
{
vx+=(acceleration_x[i-1] + acceleration_x[i])/2.0f*dt;
dx+=vx*dt;
}
and similarly for dy and dz. Here
float acceleration_x[n];
contains x-acceleration values from start to end of measurement at times 0, dt, 2*dt, 3*dt, ... (n-1)*dt.
To find the total displacement, you just do
dl=sqrt(dx*dx + dy*dy + dz*dz);
Gyroscope is not necessary for this, but if you are measuring linear distances, you can use the gyroscope reading to control that rotation of the device was not too large. If rotation was too strong, make the user re-do the measurement.
You get position by integrating the linear acceleration twice but the error is horrible. It is useless in practice.
Here is an explanation why (Google Tech Talk) at 23:20. I highly recommend this video.
Similar questions:
track small movements of iphone with no GPS
What is the real world accuracy of phone accelerometers when used for positioning?
how to calculate phone's movement in the vertical direction from rest?
iOS: Movement Precision in 3D Space
How to use Accelerometer to measure distance for Android Application Development
Distance moved by Accelerometer
Update (24 Feb 2013): #Simon Yes, if you know more about the movement, for example a person walking and the sensor is on his foot, then you can do a lot more. These are called
domain specific assumptions.
They break miserably if the assumptions do not hold and can be quite cumbersome to implement. Nevertheless, if they work, you can do fun things. See the links in my answer Android accelerometer accuracy (Inertial navigation) at indoor positioning.
You should use the Core Motion interface like described in Simple iPhone motion detect. Especially all rotations can be tracked very accurately. If you plan to do something related to linear movements this is very hard stuff. Have a look at Getting displacement from accelerometer data with Core Motion.
I took a crack at this and gave up (late at night, didn't seem to be getting anywhere). This is for a Unity3d project.
If anyone wants to pick up where I left off, I would be happy to elaborate on what all this stuff does.
Basically after some of what turned out to be false positives, I thought I'd try and filter this using a low pass filter, then attempted to remove bounces by finding a trend, then (acc_x[i-1]+acc_x[i])/2.
It looks like the false positive is still coming from the tilt, which I attempted to remove..
If this code is useful or leads you someplace, please let me know!
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// rbi.noli#gmail.com
/// </summary>
public class AccelerometerInput : MonoBehaviour
{
Transform myTransform;
Gyroscope gyro;
GyroCam gyroCam;
void Awake()
{
gyroCam= FindObjectOfType<GyroCam> ();
myTransform = transform;
if (SystemInfo.supportsGyroscope) {
gyro = Input.gyro;
gyro.enabled = true;
}
}
bool shouldBeInitialized = false;
void Update ()
{
transform.Translate (GetAccelerometer ());// * Time.deltaTime * speed);
//GetComponent<Rigidbody> ().AddForce (GetAccelerometer ());
}
public float speed = 10.0F;
public Vector3 dir;
public float f;
Vector3 GetAccelerometer()
{
dir = Input.acceleration;
dir.x *= gyro.attitude.x;
dir.z *= gyro.attitude.z;
if (Mathf.Abs (dir.x) < .001f)
dir.x = 0;
dir.y = 0;
if (Mathf.Abs (dir.z) < .001f)
dir.z = 0;
RecordPointsForFilter (dir);
//print ("Direction : " + dir.ToString("F7"));
return TestPointsForVelocity();
}
Vector3[] points = new Vector3[20];
int index;
void RecordPointsForFilter(Vector3 recentPoint)
{
if (index >= 20)
index = 0;
points [index] = EvaluateTrend (recentPoint);;
index++;
}
//try to remove bounces
float xTrend = 0;
float zTrend = 0;
float lastTrendyX = 0;
float lastTrendyZ = 0;
Vector3 EvaluateTrend(Vector3 recentPoint)
{
//if the last few points were positive, and this point is negative, don't pass it along
//accumulate points into a trend
if (recentPoint.x > 0)
xTrend += .01f;
else
xTrend -= .1f;
if (recentPoint.z > 0)
zTrend += .1f;
else
zTrend -= .1f;
//if point matches trend, keep it
if (xTrend > 0) {
if (recentPoint.x > 0)
lastTrendyX = recentPoint.x;
} else // xTrend < 0
if (recentPoint.x < 0)
lastTrendyX = recentPoint.x;
if (zTrend > 0) {
if (recentPoint.z > 0)
lastTrendyZ = recentPoint.z;
} else // xTrend < 0
if (recentPoint.z < 0)
lastTrendyZ = recentPoint.z;
return new Vector3( lastTrendyX, 0, lastTrendyZ);
}
Vector3 TestPointsForVelocity()
{
float x = 0;
float z = 0;
float xAcc = 0;
float zAcc = 0;
int successfulHits = 0;
for(int i = 0; i < points.Length; i++)
{
if(points[i]!=null)
{
successfulHits ++;
xAcc += points[i].x;
zAcc += points[i].z;
}
}
x = xAcc / successfulHits;
z = zAcc / successfulHits;
return new Vector3 (x, 0, z);
}
}
(acc_x[i-1]+acc_x[i])/2 is a low pass filter, it is the mean value between two measures in time
also look at here : http://www.freescale.com/files/sensors/doc/app_note/AN3397.pdf
pag :3
Navisens.
https://navisens.com/#how-work
Here the claim - Navisens patent-pending technology processes accelerometer and gyroscope data in a unique way to locate your phone.
Tried out the demo application, which works mostly in mapping the movements with out Location Services or WiFi once the inital location & direction are set.
iOS SDK - https://github.com/navisens/iOS-SDK
Android SDK - https://github.com/navisens/Android-SDK
Note: This is not open source
Here is the answer. Somebody asked before.
There is an app called RangeFinder doing the same thing ( available in App Store ) .