-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCricketPlayerScript.cs
More file actions
64 lines (54 loc) · 1.85 KB
/
CricketPlayerScript.cs
File metadata and controls
64 lines (54 loc) · 1.85 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using UnityEngine;
using UnityEngine.InputSystem;
public class CricketPlayerScript : MonoBehaviour
{
private float moveDirection = 0f; // -1 for left, 1 for right
private Rigidbody2D rb;
private Animator anim;
private Collider2D batCollider;
[SerializeField] private float leftBound = -0.58f;
[SerializeField] private float rightBound = 0.48f;
[SerializeField] private float hitForce = 100f;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
batCollider = GetComponentInChildren<PolygonCollider2D>();
batCollider.enabled = false;
}
private void Update()
{
rb.velocity = new Vector2(moveDirection, rb.velocity.y);
float newX = Mathf.Clamp(transform.position.x, leftBound, rightBound);
transform.position = new Vector3(newX, transform.position.y, transform.position.z);
}
public void SetDirection(float direction)
{
moveDirection = direction; // direction could be only 1 or -1
}
public void OnWeakHit()
{
anim.SetTrigger("CricketHit");
batCollider.enabled = true;
hitForce = 100f;
}
public void OnStrongHit()
{
anim.SetTrigger("CricketHit");
batCollider.enabled = true;
hitForce = 200f;
}
public void DisableBatCollider()
{
batCollider.enabled = false;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ball"))
{
Debug.Log($"Collided with: {collision.gameObject.name}");
Vector2 hitDirection = collision.contacts[0].normal; // Direction of the collision
collision.gameObject.GetComponent<Rigidbody2D>().AddForce(-hitDirection * hitForce);
}
}
}