GameObject is rotating unexpectedly

Hey,
I want my game object to translate only in x axis through accelerometer input,but it is moving in the whole plane …
Can’t figure out why?
Here is C# script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class accelmeter : MonoBehaviour {

// Use this for initialization
public float speed =10f;
Vector3 position;
public float maxpos=2.2f;
void Start () {
position = transform.position;

}

// Update is called once per frame
void Update () {
position.x += Input.acceleration.xspeedTime.deltaTime;
//float z = Input.acceleration.z;

position.x = Mathf.Clamp (position.x, -2.2f, 2.2f);
transform.Translate (tspeedTime.deltaTime,0,0);
//transform.Rotate (0, 0, -zspeedTime.deltaTime);
transform.position = position;
}
}
Please help

Hey there, please use Code Tags when pasting snippets of code. It makes it much more readable.

You seem to be mixing two different ways to apply a position change. Translate applies an offset on its own, and then you’re also setting position directly.

I don’t know what your variable “t” is there, but this should be all you need:

void Update() {
    // get the current position
    position = transform.position;

    // apply an offset
    position.x += Input.acceleration.x * speed * Time.deltaTime;

    // clamp
    position.x = Mathf.Clamp(position.x, -2.2f, 2.2f);

    // apply
    transform.position = position;
}
1 Like

Thanks alot : )

1 Like