-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCharacterFlip.cs
44 lines (38 loc) · 983 Bytes
/
CharacterFlip.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using UnityEngine;
public class CharacterFlip : MonoBehaviour
{
public Transform player; // Assign the player transform in the Inspector
private bool facingRight = true;
void Update()
{
if (player != null)
{
FlipTowardsPlayer();
}
}
void FlipTowardsPlayer()
{
float direction = player.position.x - transform.position.x;
if ((direction < 0 && !facingRight) || (direction > 0 && facingRight))
{
Flip();
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
FlipChildColliders();
}
void FlipChildColliders()
{
foreach (Collider2D col in GetComponentsInChildren<Collider2D>())
{
Vector2 offset = col.offset;
offset.x *= -1; // Flip the offset
col.offset = offset;
}
}
}