Hi guys! I'm working on a 2D platformer in which there are two playable characters that the player can toggle between and control independently. I'm having two issues with these characters regarding their movement. I would like the dark grey character to move (render) behind the light grey character, however, even when I put them on separate sorting layers (or even same sorting layer but different order in layer) they are still bumping into each other and falling all over the place. All other sorting layers are rendering fine, so I don't know why these two game objects are continuing to interact this way.
The other problem I'm having is trying to keep the entire base of the sprites in contact with the ground layer when moving. When I move the dark grey sprite, it falls over when it goes up or down hill. So I tried to freeze the rotation on the rigid body, which worked fine for the falling, but the entire base will obviously no longer be on the ground since it's frozen.
I've attached my movement code and some photos, hopefully that helps! I'm still very new to Unity, so please explain it like I'm 5 so I can understand *why* this is happening instead of just implementing a solution I don't understand.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterController : MonoBehaviour
{
//public variables
[Range(0.0f, 10.0f)] public float moveSpeed;
public float jumpForce;
public float fallMultiplier = 3.5f;
public float lowJumpMultiplier = 3f;
//private variables
Rigidbody2D _rb2d;
Transform _transform;
PolygonCollider2D _playerCollider;
float _horizontal;
bool _isFacingRight;
bool isGrounded;
// Start is called before the first frame update
void Start()
{
_rb2d = GetComponent<Rigidbody2D>();
_transform = GetComponent<Transform>();
_playerCollider = GetComponent<PolygonCollider2D>();
}
// Update is called once per frame
void Update()
{
MovePlayer();
Jump();
}
private void LateUpdate()
{
FlipSprite();
}
private void MovePlayer()
{
float horizontal = Input.GetAxis("Horizontal");
Vector2 moveVelocity = new Vector2(horizontal * moveSpeed, _rb2d.velocity.y);
_rb2d.velocity = moveVelocity;
}
private void Jump()
{
if (Input.GetButtonDown("Jump") && _playerCollider.IsTouchingLayers(LayerMask.GetMask("Ground", "Shadow", "Protagonist")))
{
_rb2d.velocity = Vector2.up * jumpForce;
}
if (_rb2d.velocity.y < 0)
{
_rb2d.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
}
else if (_rb2d.velocity.y > 0 && !Input.GetButton("Jump"))
{
_rb2d.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
}
}
private void FlipSprite()
{
bool playerIsMovingHorizontally = Mathf.Abs(_rb2d.velocity.x) > Mathf.Epsilon;
if (playerIsMovingHorizontally)
{
transform.localScale = new Vector2(Mathf.Sign(_rb2d.velocity.x), 1f);
}
}
}