As @Baste mentioned, there are significant problems with your current approach. But even if you get them fixed, there is a conceptual problem. Assuming you are checking each frame but are updating every 0.5 seconds, the data becomes stale, and your direction will only update at the rate you sample regardless of the number of times you test. I'm assuming you have a 0.5 wait because you want to average the direction over time.
An alternate approach is to use a circular buffer of positions. With 25 buffer positions being updated in FixedUpdate (running at the default speed), there will be about 1/2 second between the current position and the 'previous' position no matter when the testing is done. You can increase or decrease the time for testing by increasing or decreasing the number of buffer positions ('frameCount'). Fifty positions means 1.0 seconds for example.
In addition, I've use Vector3.Dot() to figure out the predominant direction of movement:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
Vector3[] dirs = {Vector3.up, Vector3.down, Vector3.right, Vector3.left};
string[] stDirs = {"up", "down", "right", "left"};
int frameCount = 25;
Vector3[] positions;
int currPos;
int comparePos;
void Start () {
positions = new Vector3[frameCount];
for (int i = 0; i < positions.Length; i++) {
positions[i] = transform.position;
}
currPos = frameCount -1;
comparePos = 0;
}
void FixedUpdate() {
currPos = (currPos + 1) % frameCount;
comparePos = (comparePos + 1) % frameCount;
positions[currPos] = transform.position;
}
void Update () {
int i = Direction();
if (i == -1) {
Debug.Log ("Not moving");
}
else {
Debug.Log ("Primary direction is "+stDirs[i]);
}
}
int Direction() {
Vector3 dir = positions[currPos] - positions[comparePos];
if (dir == Vector3.zero)
return -1;
int iPos = 0;
float dot = Vector3.Dot(dirs[0], dir);
for (int i = 1; i < dirs.Length; i++) {
float f = Vector3.Dot(dirs[i], dir);
if (f > dot) {
dot = f;
iPos = i;
}
}
return iPos;
}
}
↧
Trending Articles
More Pages to Explore .....