rafvasq
rafvasq

Reputation: 1522

Virtual Accelerometer in Unity

I've seen many tutorials about how to use a smartphone's accelerometer as input to control an object in Unity, but is possible to simulate a tri-axial accelerometer in Unity itself?

Upvotes: 1

Views: 578

Answers (1)

dgeyfman
dgeyfman

Reputation: 246

You can essentially get the "acceleration"(a.k.a the velocity) of an object by dividing the distance covered over time. In this case, that means breaking up a Vector3 into individual xyz variables, then calculating speed on each, and putting them back into a Vector3.

Code:

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;
}

Upvotes: 2

Related Questions