Question by
Allennick · Apr 02 at 09:11 AM ·
texturescripting beginnercollider2dmovement scripttilemap
When I flip my sprite it goes out of the tilemaps foreground
Hello everyone, I came across a problem that I can't solve. Whenever I move my character if it's near the edge of the map it goes through the tilemaps collider and goes out of the map. Here's the screenshot I took:
This is normal: link text
This is when the bug occurs: link text
Sorry if the links are of Google Drive but this site doesn't let me upload images... Here's the code I'm using to move and flip the character:
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
public class MovementScript : MonoBehaviour
{
Vector2 moveInput;
Animator animator;
Rigidbody2D rb;
BoxCollider2D myCollider;
PlayerStats playerStats;
float playerSpeed;
[SerializeField] float timeToWaitAfterBeingAttackedToMoveAgain = 1f;
[SerializeField] int kickbackFromEnemyAttack = 40;
void Start()
{
myCollider = GetComponent<BoxCollider2D>();
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
playerStats = GetComponent<PlayerStats>();
}
void FixedUpdate()
{
playerSpeed = playerStats.GetPlayerSpeed();
if(playerStats.PlayerIsAlive())
{
Run();
FlipSprite();
}
}
//If the player goes left the sprite flips left, otherwise it flips to the right
void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(rb.velocity.x) >= Mathf.Epsilon;
if(playerHasHorizontalSpeed)
{
transform.localScale = new Vector2(Mathf.Sign(rb.velocity.x), 1f);
}
}
void Run()
{
Vector2 playerVelocity = new(moveInput.x * playerSpeed, rb.velocity.y);
rb.velocity = playerVelocity;
if (myCollider.IsTouchingLayers(LayerMask.GetMask("Ground")))
{
animator.SetBool("run", Mathf.Abs(rb.velocity.x) >= Mathf.Epsilon);
}
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Enemy") && playerStats.PlayerIsAlive())
{
this.enabled = false;
TriggerKickup();
StartCoroutine(ActivateMovement());
}
}
}
Comment