- Home /
How to make slippery/smooth movement in Unity 2D?
Hi, I would like to make a slippery 2D movement for my game i'm trying to make. I've got the movement for my player character, how do I make it slippery?
Here is my movement code.
private const float MOVE_SPEED = 15f;
private Rigidbody2D rigidbody2d;
private Vector3 moveDir;
private void Awake()
{
rigidbody2d = GetComponent<Rigidbody2D>();
}
private void Update()
{
// Basic Movement for the player
float moveX = 0f;
float moveY = 0f;
if (Input.GetKey(KeyCode.W))
{
moveY = +1f;
}
if (Input.GetKey(KeyCode.S))
{
moveY = -1f;
}
if (Input.GetKey(KeyCode.A))
{
moveX = -1f;
}
if (Input.GetKey(KeyCode.D))
{
moveX = +1f;
}
moveDir = new Vector3(moveX, moveY).normalized;
}
private void FixedUpdate()
{
rigidbody2d.velocity = moveDir * MOVE_SPEED;
}
}
Answer by guubebra · Nov 04, 2021 at 06:07 PM
Hi! Try to use SmoothDamp (https://docs.unity3d.com/ScriptReference/Vector3.SmoothDamp.html) with the smoothTime at a high value.
For example:
float smoothTime = .1f;
float velocitySmoothing;
private void FixedUpdate()
{
targetVelocity = moveDir * MOVE_SPEED;
rigidbody2d.velocity = Time.deltaTime * Mathf.SmoothDamp(velocity, targetVelocity, ref velocitySmoothing, smoothTime);
}
Answer by Abyssal_Epicc · Mar 17 at 09:39 PM
you can make it really slippery by just adding force to the rigidbody
// For moving right, simplified version though, add whatever you please
rigidbody2d.AddForce(Vector2.right);
Your answer
Follow this Question
Related Questions
Player is not moving 0 Answers
How do i make a cube move (Continuosly without stopping) when i press a button once in unity 2D 2 Answers
How to flip, on click a constant moving 2d rigidbody on the x-axis and maintain speed? 0 Answers
Why do GameObjects need Rigidbodies to collide? 0 Answers
How to use non-convex mesh collider with dynamic rigid body physics? 1 Answer