Alright, so I’ve been looking through all of the things Unity has on movement and 2D movement. I’ve looked at other people’s examples, and I’ve looked through countless code snippets, but I cannot for the life of me find a way to make my character’s movement precise.
By precise, I mean, have it stop the second you let go of a key, and begin the second you push down on a key. I don’t want it to accelerate or decelerate. I want it to move at a set value constantly.
Right now, I’ve got it setup this way:
void Update ()
{
//cache vertical input
float vertical = Input.GetAxis("Vertical");
//assign vertical input as a vector 2 value
Vector2 movement = new Vector2 (0.0f, vertical);
//use vector 2 value to add force
rigidbody2D.AddForce (movement);
}
Using this, I get movement, but it is weighty and the character does not stop moving after input is pressed because a force is still acting on the player character.
I have tried alleviating this in a number of ways.
One of these was to set up a simple set of if/else statements in order to find input, and then to assign a rigidbody2D.velocity.y directly, like below:
float speed = 10;
// Update is called once per frame
void Update ()
{
if (Input.GetKey("w"))
{
rigidbody2D.velocity.y = speed;
}
else if (Input.GetKey("s"))
{
rigidbody2D.velocity.y = speed * -1;
}
else
{
rigidbody2D.velocity.y = 0;
}
}
This however pops up with an error in Unity asking me to store the variable in a temporary variable. And so, I have tried to do this by writing it this way:
float speed = 10;
// Update is called once per frame
void Update ()
{
Vector2 velocity = rigidbody2D.velocity;
rigidbody2D.velocity = velocity;
if (Input.GetKey("w"))
{
velocity.y = speed;
}
else if (Input.GetKey("s"))
{
velocity.y = speed * -1;
}
else
{
velocity.y = 0;
}
}
However, when I do this, I try to move the character with “w” or “s” and nothing happens, it is stationary. Any help you guys could give me would be greatly appreciated!