Hi, everyone
can anyone please explain the following code:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public float speed = 10.0F;
void Update() {
Vector3 dir = Vector3.zero;
dir.x = -Input.acceleration.y;
dir.z = Input.acceleration.x;
if (dir.sqrMagnitude > 1)
dir.Normalize();
dir *= Time.deltaTime;
transform.Translate(dir * speed);
}
}
I want an explanation because it did work but not properly when i tried it in my game, so understanding may help me understand what is the issue.
Thank you all for your time.
Source: Unity - Scripting API: Input.acceleration
3 Answers
3
With comments…
// Assume that device is held parallel to the ground
// and Home button is in the right hand
// remap device acceleration axis to game coordinates:
// 1) XY plane of the device is mapped onto XZ plane
// 2) rotated 90 degrees around Y axis
dir.x = -Input.acceleration.y;
dir.z = Input.acceleration.x;
// Clamp acceleration vector to unit sphere
if (dir.sqrMagnitude > 1)
dir.Normalize();
// Make it move 10 meters per second instead of 10 meters per frame...
dir *= Time.deltaTime;
// Move object
transform.Translate (dir * speed);
I believe Input.acceleration returns data from anything using an accelerometer. That is, an input device moving through 3D space in real-life that can report that info to Unity. Something like a phone with an accelerometer or any other peripherals that have one.
What exactly are you wanting to do with this code?
It won’t necessarily do anything if you don’t have the proper inputs, or if it’s not running on a device with an accelerometer.
If you want basic input for keyboard / gamepad, try
float xInput = Input.GetAxis("Horizontal");
float yInput = Input.GetAxis("Vertical");
I have just recently discovered how to do this. The code is wrong. transform.Translate for me at least doesn’t work. Use: GetCompenent().AddForce(dir); Please let me know if this has helped.
We would also like some explanation on what is not working.
– fafaseso when i start the scene the object just starts moving by itself in different directions and i have no control over it. Notice that the mobile is put on flat surface without me touching it, i guess the object should not move unless i touch the mobile.If i try to move the object using the mobile it doesn't move in the proper directions so what explains that irregular behavior? May u please try the code and see if it works? I think if i understand the code i would be able to fix it :) Thank you for your participation.
– DatabasesI have had this problem for ages and would love an explanation! My character only moves when the line of code: transform.Translate(dir * speed) is put in. It similarly spins uncontrollably.
– semaj678