I am stuck on the code for couple of days but couldn’t figure it out. Therefore I turned out to look the answer here but couldn’t find any that match the requirement Hope some One might help

here is the code

``````    /*  Part1
*Step Horizontal Movement
* Use to get left and right movement
*/
if(Input.GetKey ("right")||Input.GetKey ("left")){
moveDir.x = Input.GetAxis("Horizontal"); // get result of AD keys in X
}
rigidbody.velocity = moveDir * speed;

/*Part2
*Continuse Forward Movement
*/
if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
{
moveDir.z = Input.GetAxis("Vertical");
}
``````

I have a Cube with added rigidBody Component. When pressed left or right key the cube should move in that direction and when key is released it should stop Part one when run commenting part2 code runs correctly

the other movement that I am trying to achieve is the cube should move continuously.But the thing is when pressed up key it should increase the magnitude and when released it should maintain the magnitude and move constantly.This is also achieved successfull with the part2 code by commenting part1 code
But when but run without commenting any of them part1 results are correct but part2 does not provide correct result which was obtained by commenting part1 code

Is there any other way to obtain the same reult

You don’t give me enough code to tell if you are using Javascript or C#. Here is a C# solution (untested):

``````	Vector3 vel = rigidbody.velocity;
vel.x = Input.GetAxisRaw("Horizontal") * speed;
rigidbody.velocity = vel;

rigidbody.AddForce (Vector3.forward * Input.GetAxis("Vertical") * 50.0f);
``````

First the Input.GetKey() tests are unnecessary. If you look at how the Horizontal and Vertical Axes are defined, you will see they have the keys you are using defined. Also there is a GetAxisRaw() that gets the the raw data. GetAxis() is buffered a bit. You may like the way your game feels with GetAxis() rather than GetAxisRaw(), but your question indicated an immediate stop.

Note the way this problem is solves is to have part 1 only manipulate the ‘x’ axis, and part 2 only manipulate the ‘z’ axis of the object.

If you are using Javascript/Unityscript, it can be simplified to:

``````	rigidbody.velocity.x = Input.GetAxisRaw("Horizontal") * speed;

rigidbody.AddForce (Vector3.forward * Input.GetAxis("Vertical") * 50.0f);
``````