2D moving Script
So i try to make a simple movement script, the player is not effected by gravity ( but yes i have a ridgidbody2d attached to him) I dont want to do a Platformer, the player just should go upwards, downwards, right, left and diagonal here is my script so far
public float horizontal;
public float vertical;
void Start () {
}
void Update () {
if (Input.GetKey(KeyCode.W))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, vertical);
}
if (Input.GetKey(KeyCode.S))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, -vertical);
}
if (Input.GetKey(KeyCode.A))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-horizontal, GetComponent<Rigidbody2D>().velocity.y);
}
if (Input.GetKey(KeyCode.D))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(horizontal, GetComponent<Rigidbody2D>().velocity.y);
}
}
}
everything is fine, until i try to move the player diagonal. It moves diagonal but i cant get back to the left, right, up and down
Answer by Dave-Carlile · Oct 13, 2015 at 12:58 PM
The issue is that you never set a velocity value back to 0 when the key is released. A simple solution is to set the Rigidbody's velocity to 0 at the beginning of Update and then change it based on the current keys. But this will have the side effect that if no keys are pressed then it won't move at all. Is that the behavior you're looking for?
Another word of advice which will make your code simpler. Add a field to the class to hold a reference to the rigid body component. Set it in Start...
Rigidbody2D rigidBody;
void Start()
{
rigidBody = GetComponent<RigidBody2D>();
}
Now in Update you can just use the rigidbody
field instead of having to call GetComponent all of the time. This will help performance (because GetComponent has a lot of work to do to find the component) and make your code very much more readable and easier to maintain.
thank you, the first answere was exactly what i was looking for