- Home /
Question by
poncegabby0 · Apr 14, 2021 at 01:13 PM ·
c#movementmovement scriptwalkingfloating
When I jump then walk, my character suddenly starts walking mid-air...
When I jump then start walking to either side, the character just keeps walking midair floating, and when i walk while the jumping is still happening, it stops the y movement and makes me float while walking again. Here's my code:
public Rigidbody2D rb;
public float speed = 10f;
public float jumpHeight = 100f;
public Animator anim;
public Transform groundCheck;
public float groundDistance = 0.4f;
bool isGrounded;
public LayerMask groundMask;
Vector2 velocity;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundDistance, groundMask);
float x = Input.GetAxisRaw("Horizontal");
if(x > 0)
{
transform.localScale = new Vector2(1, 1);
}
else if(x < 0)
{
transform.localScale = new Vector2(-1, 1);
}
if(isGrounded && Input.GetButtonDown("Jump"))
{
rb.AddForce(Vector2.up * jumpHeight);
}
}
void FixedUpdate()
{
float x = Input.GetAxisRaw("Horizontal");
Vector3 move = transform.right * x;
Vector2 direction = new Vector2(x, 0f).normalized;
if(Math.Abs(direction.magnitude) >= 0.1f)
{
anim.SetBool("isRunning", true);
rb.MovePosition(transform.position + move.normalized * speed * Time.deltaTime);
}
else if(direction.magnitude == 0f)
{
anim.SetBool("isRunning", false);
}
}
Comment
Best Answer
Answer by HellsHand · Apr 14, 2021 at 01:21 PM
You only want to receive movement inputs if isGrounded = true
. A basic example:
float x = 0f;
if(isGrounded)
{
x = Input.GetAxisRaw("Horizontal");
}