Reputation: 35
I'm starting to learn unity and I am facing a problem I can't get rid of, which is: however I tried to make the movement smooth it's not like usual video games, no matter how high the FPS is or how many different ways I try to implement the logic.
I tried to use fixed update and fixed delta time but nothing seems to make a difference.
void Update()
{
movement = Input.GetAxis("Horizontal");
if ((movement > 0 && lookingLeft) || (movement < 0 && !lookingLeft))
{
lookingLeft = !lookingLeft;
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
}
if (noOfJumps > 0 || jumping)
jumpInput = Input.GetAxis("Jump");
if (jumpInput > 0 && !jumping)
{
pressTime = 0;
jumping = true;
noOfJumps--;
}
else if (jumpInput == 0)
jumping = false;
else
pressTime += Time.deltaTime;
if (pressTime > 0.15f)
jumpInput = 0;
}
private void FixedUpdate()
{
rd.velocity = Vector2.Lerp(rd.velocity, new Vector2(movement != 0 ? speed *
movement * Time.fixedDeltaTime : rd.velocity.x * 0.95f, (jumpInput != 0) ? jumpInput * jumpSpeed * Time.fixedDeltaTime : -1), 0.9f);
}
Upvotes: 3
Views: 3713
Reputation: 31
I think that the problem is in the way you get the input from the user.
If you use Input.GetAxis("Horizontal") this will give you a value BETWEEN -1 and 1 and that value will be proportional to how hard or how long has the player been pressing the button.
Try using .GetAxisRaw() instead of .GetAxis(), this way you will just get the value -1 or 1 depending on the direction the player is moving and this will result in a more snappier movement
movement = Input.GetAxisRaw("Horizontal");
Check this video on the topic
Upvotes: 3
Reputation: 20269
Assigning directly to velocity can overwrite certain calculations each frame. Best to use AddForce
to avoid overriding changes due to gravity & friction.
Let the smoothing that Input.GetAxis
puts into movement
do the smoothing for you. Just multiply that value by speed to get the new horizontal speed.
Also, you're changing velocity, so you don't need to multiply your speed field by Time.fixedDeltaTime
.
private void FixedUpdate()
{
float newVerticalVelocity = rd.velocity.y + jumpInput * jumpSpeed;
Vector2 velocityChange = newVerticalVelocity * Vector2.up
+ movement * speed * Vector2.right
- rd.velocity;
rd.AddForce(velocityChange, ForceMode.VelocityChange);
}
Upvotes: 2