- Home /
Trouble with moving cube when key is pressed
Hi all,
I have been following a tutorial which explains how to create a 'runner' style game; but I do not want my cube to constantly be in motion. INstead I want it to move when I press 'd'.
Here is the script:
using UnityEngine; using System.Collections;
public class RunnerScript : MonoBehaviour {
public float accelaration = 5;
public float maxSpeed = 10;
private bool touchGround = false;
public Vector3 JumpVel;
public Vector3 ForwardVel;
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Jump") && touchGround){
rigidbody.AddRelativeForce(JumpVel, ForceMode.VelocityChange);
touchGround = false;
}
var currentSpeed = rigidbody.velocity;
currentSpeed.y = 0;
//Here is where I am having trouble
if (touchGround && currentSpeed.magnitude < maxSpeed){
rigidbody.AddRelativeForce(accelaration, 0, 0);
}
//To here
}
//If the player touches the ground
void OnCollisionEnter(){
touchGround = true;
}
}
See the comment '//Here is where I am having trouble', that is currently what I am using to move the cube; which works fine in a sense. But when I put the condition 'Input.getKeyDown('d))' on the end of that; it does not work.
Anyone have any suggestions?
Thanks,
Callum
/ UPDATE /
Ok, I now have it moving when i press a key; but the issue now is that it only moves when i press and release the key. Like it is only happening once every update.
Is there a way to have it so that when i hold the key down, the cube moves?
Thanks.
The code I am using:
if (Input.GetKeyDown("d")){ currentSpeed.x = 100;
rigidbody.AddRelativeForce(accelaration, 0, 0); }
Answer by robertbu · Aug 24, 2013 at 04:13 PM
There are a couple of ways you can deal with this issue. The first is you use GetKeyDown() and GetKeyUp() to set the velocity:
if (Input.GetKeyDown(KeyCode.D)) {
Vector3 vel = new Vector3(10.0f, 0.0f, 0.0f);
vel = transform.TransformDirection(vel);
rigidbody.velocity = vel;
}
if (Input.GetKeyUp(KeyCode.D)) {
rigidbody.velocity = Vector3.zero;
}
An alternate solution would be to crank up the 'Drag' setting of the rigidbody in the inspector to something like 15. Then you use this code instead.
if (Input.GetKey(KeyCode.D)) {
Vector3 vel = new Vector3(10.0f, 0.0f, 0.0f);
vel = transform.TransformDirection(vel);
rigidbody.velocity = vel;
}
This will result in a small amount of movement after the key is lifted, which often looks more natural.
Your answer
![](https://koobas.hobune.stream/wayback/20220613112902im_/https://answers.unity.com/themes/thub/images/avi.jpg)