OK I have a strange behaviour where, when the game starts, I detect the player not on the Ladder/Climbing layout but as soon as it touches the ground, it detects as if it was touching the Climb layer.
Here’s my player code, it is slightly different than what’s on the course mind you:
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class Player : MonoBehaviour
{
#region Serialized Fields
[SerializeField]
private float maxSpeed = 5f;
[SerializeField]
private float jumpForce = 5f;
[SerializeField]
private float climbSpeed = 3f;
#endregion
#region Public Fields
#endregion
#region Private Fields
private Rigidbody2D myRigidbody;
private Animator myAnimator;
private Collider2D myCollider2D;
private bool isAlive = true;
private bool isRunning = false;
private bool isOnLadder = false;
#endregion
#region Unity Methods
private void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
myCollider2D = GetComponent<CapsuleCollider2D>();
}
private void Update()
{
LookForward();
HorizontalMove();
Jump();
ClimbMove();
UpdateAnimation();
}
#endregion
#region Private Methods
private void LookForward()
{
if (isRunning = HasHorizontalMovement())
{
transform.localScale = new Vector2(Mathf.Sign(myRigidbody.velocity.x), transform.localScale.y);
}
}
private void HorizontalMove()
{
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
Vector2 playerVelocity = new Vector2(horizontal * maxSpeed /** Time.deltaTime*/, myRigidbody.velocity.y);
myRigidbody.velocity = playerVelocity;
}
private void Jump()
{
if (!myCollider2D.IsTouchingLayers(LayerMask.GetMask("Ground"))) return;
if (CrossPlatformInputManager.GetButtonDown("Jump"))
{
Vector2 jumpVelocityToAdd = new Vector2(0f, jumpForce);
myRigidbody.velocity += jumpVelocityToAdd;
}
}
private void ClimbMove()
{
isOnLadder = myCollider2D.IsTouchingLayers(LayerMask.GetMask("Ladders"));
if (!isOnLadder)
{
myRigidbody.gravityScale = 1f;
return;
}
else
{
myRigidbody.gravityScale = 0f;
float movement = CrossPlatformInputManager.GetAxis("Vertical");
Vector2 climbVelocity = new Vector2(myRigidbody.velocity.x, movement * climbSpeed);
myRigidbody.velocity = climbVelocity;
}
}
private void UpdateAnimation()
{
myAnimator.SetBool("IsRunning", isRunning);
myAnimator.SetBool("IsClimbing", isOnLadder);
print(isOnLadder);
}
private bool HasHorizontalMovement()
{
return Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon;
}
I set the isOnLadder bool only once, in the ClimbMove method, when I try to “watch” IsTouchingLayers in VS, it gives back an error, but it puts true in isOnLadder…
Why is this happenning?