Sometimes my Player does not want to touch the Ladder. It happens not often, but sometimes he even falls from it.
Input works, but player does not touch the ladder.
Collision detection for player is:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
Vector2 moveInput;
Rigidbody2D myRigidbody;
Animator myAnimator;
CapsuleCollider2D myCollider;
[SerializeField] float runSpeed = 5f;
[SerializeField] float jumpStrength = 10f;
[SerializeField] float climbSpeed = 3f;
float gravityScaleAtStart;
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
myCollider = GetComponent<CapsuleCollider2D>();
gravityScaleAtStart = myRigidbody.gravityScale;
}
void Update()
{
Run();
FlipSprite();
ClimbLadder();
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
Debug.Log(moveInput);
}
void OnJump(InputValue value)
{
if(!myCollider.IsTouchingLayers(LayerMask.GetMask("Ground"))) { return; }
if(value.isPressed)
{
myRigidbody.velocity += new Vector2 (0f, jumpStrength);
}
}
void ClimbLadder()
{
if(!myCollider.IsTouchingLayers(LayerMask.GetMask("Ladder")))
{
myRigidbody.gravityScale = gravityScaleAtStart;
myAnimator.SetBool("isClimbing", false);
Debug.Log("NoT on the ladder");
return;
}
Vector2 climbVelocity = new Vector2 (myRigidbody.velocity.x, moveInput.y * climbSpeed);
myRigidbody.velocity = climbVelocity;
myRigidbody.gravityScale = 0f;
bool playerIsClimbing = Mathf.Abs(myRigidbody.velocity.y) > Mathf.Epsilon;
myAnimator.SetBool("isClimbing", playerIsClimbing);
Debug.Log("On the ladder");
}
void Run()
{
Vector2 playerVelocity = new Vector2 (moveInput.x * runSpeed, myRigidbody.velocity.y);
myRigidbody.velocity = playerVelocity;
bool platerHasHorisontalSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon;
myAnimator.SetBool("isRunning", platerHasHorisontalSpeed);
}
private void FlipSprite()
{
bool platerHasHorisontalSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon;
if(platerHasHorisontalSpeed){
transform.localScale = new Vector2 (Mathf.Sign(myRigidbody.velocity.x), 1f);
}
}
}