- Home /
alternative to using horizontal/vertical
Just a quick question. How would you code something that would have the same effect as this code, with the smoothing at the end and everything, but without using the horizontal/vertical and without using physics? (using the a and d keys)
function Update ()
{
transform.Translate (Input.GetAxis ("Horizontal"), 0, 0);
}
Thanks!
more info as requested :)
Yes, I want to translate an object based on a button input, but smoothed out.. I want to know how the code works so I can try to apply it to other things, like, smooth scale in/out based on holding the left/right button, or smooth offset a texture based on how long I hold a button, etc.
Thanks!
Could you explain exactly what you want to do in a bit more detail? For example, do you want to translate an object based on a button input, but smoothed out?
Answer by Mike 3 · Nov 11, 2010 at 03:42 PM
You'd use something along the lines of this:
var speed : float = 3; //just to make it a lil more configurable
function Update () { var horizontal = 0; if (Input.GetKey(KeyCode.A)) horizontal = -1; if (Input.GetKey(KeyCode.D)) horizontal += 1; transform.Translate (horizontal speed Time.deltaTime, 0, 0); }
With smoothing:
var speed : float = 3; //just to make it a lil more configurable var currentHorizontal : float = 0;
function Update () { var horizontal = 0; if (Input.GetKey(KeyCode.A)) horizontal = -1; if (Input.GetKey(KeyCode.D)) horizontal += 1; currentHorizontal = Mathf.Lerp(currentHorizontal, horizontal, Time.deltaTime); transform.Translate (currentHorizontal speed Time.deltaTime, 0, 0); }
can you please explain how this will work what does horizontal = -1, and horizontal +=1 works
it's just an int, when used in translate as x, -1 goes left, +1 goes right
Your answer
![](https://koobas.hobune.stream/wayback/20220613082735im_/https://answers.unity.com/themes/thub/images/avi.jpg)