- Home /
Question by
erasergame · Oct 11, 2020 at 03:56 PM ·
movementinputmovement scriptaxis
How to get Horizontal axis value to 0 instantly after releasing the positive button!!!!
I'm facing a problem in which my horizontal axis takes time to reach 0 if positive button is pressed for a while I've tried everything but I runs good for 1 or 2 times I playtest. How do i deal with it? PLS HELP..... My CODE: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerMovement : MonoBehaviour { [SerializeField] private float jumpForce = 5f; [SerializeField] private float walkSpeed = 5f; [SerializeField] private float maxFallSpeed = -25f;
private Rigidbody rbody;
//Input variables
private float horizontalInput;
private bool isGrounded;
private bool inAir;
private bool playerJumpped;
public bool canMove;
// Start is called before the first frame update
void Start()
{
rbody = GetComponent<Rigidbody>();
canMove = true;
}
// Update is called once per frame
void Update()
{
//Jumping the character
if (Input.GetKeyDown(KeyCode.Space) && isGrounded && !inAir)
{
playerJumpped = true;
}
//stopping the player
if (Input.GetKeyUp(KeyCode.D) || Input.GetKeyUp(KeyCode.A))
{
canMove = false;
}
horizontalInput = Input.GetAxisRaw("Horizontal");
horizontalInput = Mathf.Clamp(horizontalInput, -1f, 1f);
}
void FixedUpdate()
{
float _velocity = rbody.velocity.magnitude;
// Managing Player Movement
rbody.constraints = RigidbodyConstraints.FreezeRotation;
if (_velocity > maxFallSpeed) // Setting Velocity to constant value or Setting velocity limit (Limit is = ?)
{
rbody.velocity = Vector3.ClampMagnitude(rbody.velocity, maxFallSpeed);
}
if(canMove == true && horizontalInput != 0f) //Moving the character
{
rbody.velocity = new Vector3(horizontalInput * walkSpeed, rbody.velocity.y , 0f);
}
if (canMove == false && horizontalInput == 0f) //Stopping the character
{
rbody.velocity = new Vector3(0f, rbody.velocity.y, 0);
rbody.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezeRotation;
canMove = true;
}
//Jumping the character
if (playerJumpped == true)
{
rbody.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
playerJumpped = false;
}
}
void OnCollisionStay()
{
isGrounded = true;
inAir = false;
}
void OnCollisionExit()
{
isGrounded = false;
inAir = true;
}
}
Comment