- Home /
Rookie Problem: transform.translate
Hello,
I'm having some trouble with the code below. I'm trying to set up the vertical movement of a gameObject. The problem is, when I press 'S', the gameobject moves once, then stops. I thought that putting the input check inside the update loop would have it called once per frame, thereby creating continuous movement. Any help would be appreciated!
using UnityEngine;
using System.Collections;
public class PlayerPaddle : MonoBehaviour
{
public int speed;
// Use this for initialization
void Start ()
{
speed = 100;
}
// Update is called once per frame
void Update ()
{
if(Input.GetKeyDown(KeyCode.S))
{
transform.Translate(0, -speed * Time.deltaTime, 0);
}
}
}
Answer by chelnok · Nov 14, 2012 at 08:23 PM
You need to change this line:
if(Input.GetKeyDown(KeyCode.S))
to:
if(Input.GetKey(KeyCode.S))
Indeed. Anyway, Screenhog (and me too) would rather do this with GetAxis. Why? Justbecause.. getaxis / getbutton is kind of extended hardCoded$$anonymous$$ey.S. You can make your own kind of button (or axis) like named $$anonymous$$oveDown. You can set your axis / buttons in input manager. You may allow to player also use pad, joystick, whatever.. and all those be mapped to button($$anonymous$$oveDown) or something like that. It took a while for me to approve the consept, but now when i do, i like it better this way. $$anonymous$$ore info: http://docs.unity3d.com/Documentation/Components/class-Input$$anonymous$$anager.html
Yep, after messing with it, I see what you mean. Thanks again!
Answer by Screenhog · Nov 14, 2012 at 07:53 PM
You're using GetKeyDown, which "Returns true during the frame the user starts pressing down the key identified by name."
I would instead do this:
void Update ()
{
transform.Translate(0, Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0);
}
This will use the Horizontal axis to apply movement both upwards and downwards (see Project Settings > Input). The Horizontal Axis automatically uses W for up and S for down (as well as the arrow keys).
Thanks for the pointer!
Starting to see the merit of this now after fiddling around with it. Very tidy code. Thanks again!
Your answer
![](https://koobas.hobune.stream/wayback/20220613083851im_/https://answers.unity.com/themes/thub/images/avi.jpg)