- Home /
Help on Player Movement Script C#
Hi, I'm having some difficulties with moving script. Wanted behavior is that Player object can move in all directions, and gravity is 0. Also speed of the object should decrease slowly, so I tried to accomplish that with drag.
What happens is this, if i set it too low, object just goes and needs few seconds to fully stop, but if I put it higher it stops almost instantly, and something in the middle looks pretty strange.
Is there a better way to accomplish this?
void FixedUpdate () {
if (Input.GetKey(KeyCode.W)) {
rigidbody2D.AddForce(Vector2.up * forceConstant);
animator.SetFloat("verticalSpeed", 1);
} else if (Input.GetKey(KeyCode.S)) {
rigidbody2D.AddForce(Vector2.up * -forceConstant);
animator.SetFloat("verticalSpeed", 1);
}
if(Input.GetKey(KeyCode.A)){
rigidbody2D.AddForce(Vector2.right * -forceConstant);
animator.SetFloat("horizontalSpeed", 1);
}else if(Input.GetKey(KeyCode.D)){
rigidbody2D.AddForce(Vector2.right * forceConstant);
animator.SetFloat("horizontalSpeed", 1);
}
if(Input.GetKeyUp(KeyCode.W))
{
animator.SetFloat("verticalSpeed", 0);
rigidbody2D.drag = 25f;
}
if(Input.GetKeyUp(KeyCode.A))
{
animator.SetFloat("horizontalSpeed", 0);
rigidbody2D.drag = 25f;
}
if(Input.GetKeyUp(KeyCode.S))
{
animator.SetFloat("verticalSpeed", 0);
rigidbody2D.drag = 25f;
}
if(Input.GetKeyUp(KeyCode.D))
{
animator.SetFloat("horizontalSpeed", 0);
rigidbody2D.drag = 25f;
}
}
Comment
Try tweaking the mass as well. Your trouble probably stems from physics settings.