- Home /
Android Tilt controls help
So i'm developing a game where you can move the spaceship only on the x-axis like space invaders. So i am having a little trouble trying to implent tilt controls, i have google searched constantly and i looked into the unity manual, everytime i test out my game the ship disappears. Here is my code for movement right now i have it set for keyboard commands because the accelerometer wasnt working
function Update () {
if(Input.GetAxis("Horizontal") > 0){
if (collided_with != null){
if (collided_with.tag == "Left"){
return;
}
}
transform.Translate(Vector3(1 * speed * Time.deltaTime,0,0));
}
if(Input.GetAxis("Horizontal") < 0 ){
if (collided_with != null){
if (collided_with.tag == "Right"){
return;
}
}
transform.Translate(Vector3(-1 * speed * Time.deltaTime,0,0));
}
If you can help thank you!
Answer by iamvishnusankar · May 03, 2014 at 06:22 AM
The reason of spaceship going off screen might cause you've haven't clamped the position to a particular value. Here's a solution, Hope this will help to solve your problem.
function Update()
{
var dir : Vector2 = Vector2.zero;
dir.x = Input.acceleration.x;
dir.y = 0;
// 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);
//Clamp transform position
//Here transform's x position will get clamped to a value of -3 to 3 change it as per your requirement
transform.position = Vector2(Mathf.Clamp(transform.position.x,-3,3),
0);
}
Thank you!
But just 2 things i forgot to mention im using portrait mode for my game and when i test out the script it worked but everything was invereted(ex. Left was right, and right was left) and it placed my gameobject out of the game scene where nothing could collide with it.
Your answer
Follow this Question
Related Questions
Face Direction of Tilting 1 Answer
How to calibrate my accelerometer? (available options not working) 0 Answers
Accelerometer question 1 Answer