Hello, I’m new to unity and I’m having this problem. I’m trying to figure out how to make it so my player will stop playing its jump animation while it is colliding with the ground but I am still not sure on how to write that code. It might be that I’m writing it wrong or something else but I have already tried to say if its grounded, but that did nothing at all. I have also tried putting it in other stops of my code to see if it would work but that did nothing at all. I already have to jumping animation set its just I want to know how to stop it.
My player code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PM : MonoBehaviour
public float moveSpeed;
public float jumpHeight;
Rigidbody2D rb;
BoxCollider2D boxColliderPlayer;
int layerMaskGround;
float heightTestPlayer;
public Animator animator;
void Start()
{
rb = GetComponent<Rigidbody2D>();
// Get the player's collider so we can calculate the height of the character.
boxColliderPlayer = GetComponent<BoxCollider2D>();
// We do the height test from the center of the player, so we should only check
// halft the height of the player + some extra to ignore rounding off errors.
heightTestPlayer = boxColliderPlayer.bounds.extents.y + 0.05f;
// We are only interested to get colliders on the ground layer. If we would
// like to jump ontop of enemies we should add their layer too (which then of
// course can't be on the same layer as the player).
layerMaskGround = LayerMask.GetMask("Ground");
}
void Update()
{
/// Player movement and playing the animtion
float moveDir = Input.GetAxis("Horizontal") * moveSpeed;
rb.velocity = new Vector2(moveDir, rb.velocity.y);
animator.SetFloat("Speed",Mathf.Abs(moveDir));
// Your jump code:
if (Input.GetKeyDown("space") && IsGrounded() )
{
rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
////////// Telling it to play my jump anitmion
animator.SetBool(“isJump”, true);
}
//Telling it to rotate my animtion's
Vector3 characterScale = transform.localScale;
if (Input.GetAxis("Horizontal")< 0){
characterScale.x = -3;
}
if (Input.GetAxis("Horizontal")> 0){
characterScale.x = 3;
}
transform.localScale = characterScale;
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Coins"))
{
Destroy(other.gameObject);
}
}
/// <summary>
/// Simple check to see if our character is no the ground.
/// </summary>
/// <returns>Returns <c>true</c> if the character is grounded.</returns>
private bool IsGrounded()
{
// Note that we only check for colliders on the Ground layer (we don't want to hit ourself).
RaycastHit2D hit = Physics2D.Raycast(boxColliderPlayer.bounds.center, Vector2.down, heightTestPlayer, layerMaskGround);
bool isGrounded = hit.collider != null;
// It is soo easy to make misstakes so do a lot of Debug.DrawRay calls when working with colliders...
Debug.DrawRay(boxColliderPlayer.bounds.center, Vector2.down * heightTestPlayer, isGrounded ? Color.green : Color.red, 0.5f);
return isGrounded;
}
}