Unity 中的虚拟加速度计
Virtual Accelerometer in Unity
我看过很多关于如何使用智能手机的加速度计作为输入来控制 Unity 中的对象的教程,但是可以在 Unity 本身中模拟三轴加速度计吗?
您基本上可以通过除以随时间推移的距离来获得对象的“加速度”(a.k.a 速度)。在这种情况下,这意味着将 Vector3 分解为单独的 xyz 变量,然后计算每个变量的速度,然后将它们放回 Vector3。
代码:
Vector3 lastPos;
void Start() {
lastPos = transform.position;
}
void Update() {
// define velocities as currentPos-lastPos(change) over time per frame, which gets velocity this frame... will be saved every frame
float xVelocity = (transform.position.x-lastPos.x)/Time.deltaTime;
float yVelocity = (transform.position.y-lastPos.y)/Time.deltaTime;
float zVelocity = (transform.position.z-lastPos.z)/Time.deltaTime;
// Do stuff with individual velocities(xyz)
// ...
// or store in Vector3
Vector3 totalVelocity = new Vector3(xVelocity, yVelocity, zVelocity);
// Do stuff with total velocity
// ...
// Set lastPos to transform.position (WARNING: Only do after you are done calculating velocity
lastPos = transform.position;
}
我看过很多关于如何使用智能手机的加速度计作为输入来控制 Unity 中的对象的教程,但是可以在 Unity 本身中模拟三轴加速度计吗?
您基本上可以通过除以随时间推移的距离来获得对象的“加速度”(a.k.a 速度)。在这种情况下,这意味着将 Vector3 分解为单独的 xyz 变量,然后计算每个变量的速度,然后将它们放回 Vector3。
代码:
Vector3 lastPos;
void Start() {
lastPos = transform.position;
}
void Update() {
// define velocities as currentPos-lastPos(change) over time per frame, which gets velocity this frame... will be saved every frame
float xVelocity = (transform.position.x-lastPos.x)/Time.deltaTime;
float yVelocity = (transform.position.y-lastPos.y)/Time.deltaTime;
float zVelocity = (transform.position.z-lastPos.z)/Time.deltaTime;
// Do stuff with individual velocities(xyz)
// ...
// or store in Vector3
Vector3 totalVelocity = new Vector3(xVelocity, yVelocity, zVelocity);
// Do stuff with total velocity
// ...
// Set lastPos to transform.position (WARNING: Only do after you are done calculating velocity
lastPos = transform.position;
}