-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayerController.cs
More file actions
69 lines (57 loc) · 1.59 KB
/
PlayerController.cs
File metadata and controls
69 lines (57 loc) · 1.59 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
65
66
67
68
69
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody2D rb;
private float gravityScale;
public LayerMask groundLayer;
public float JumpForce = 10;
public float MoveSpeed = 3;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private Vector2 velocity;
private float rawY = 0;
private void FixedUpdate()
{
// Get x-input
float xInput = Input.GetAxisRaw("Horizontal");
velocity.x = xInput * MoveSpeed;
// Change gravity scale based on player state
if (rb.velocity.y < 0)
gravityScale = 0.2f;
else
gravityScale = 0.1f;
// Add gravity
rawY += Physics2D.gravity.y * gravityScale;
velocity.y = Mathf.Clamp(rawY, -15, 15);
if((int)rb.velocity.y == 0)
{
rawY = 0;
}
// Set velocity
rb.velocity = velocity;
if(IsGrounded() && Input.GetAxisRaw("Vertical") == 1)
{
Jump();
}
}
// Jump function
void Jump()
{
rawY = JumpForce;
}
// Is grounded code (altered from https://kylewbanks.com/blog/unity-2d-checking-if-a-character-or-object-is-on-the-ground-using-raycasts)
bool IsGrounded()
{
Vector2 position = transform.position;
Vector2 direction = Vector2.down;
float distance = 0.9f;
RaycastHit2D hit = Physics2D.Raycast(position, direction, distance, groundLayer);
if (hit.transform != null)
{
return true;
}
return false;
}
}