-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayerController2D.cs
More file actions
78 lines (69 loc) · 2.53 KB
/
PlayerController2D.cs
File metadata and controls
78 lines (69 loc) · 2.53 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
70
71
72
73
74
75
76
77
78
using UnityEngine;
public class PlayerController2D : MonoBehaviour
{
// Public variables
public float speed = 5f; // The speed at which the player moves
public bool canMoveDiagonally = true; // Controls whether the player can move diagonally
// Private variables
private Rigidbody2D rb; // Reference to the Rigidbody2D component attached to the player
private Vector2 movement; // Stores the direction of player movement
private bool isMovingHorizontally = true; // Flag to track if the player is moving horizontally
void Start()
{
// Initialize the Rigidbody2D component
rb = GetComponent<Rigidbody2D>();
// Prevent the player from rotating
rb.constraints = RigidbodyConstraints2D.FreezeRotation;
}
void Update()
{
// Get player input from keyboard or controller
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
// Check if diagonal movement is allowed
if (canMoveDiagonally)
{
// Set movement direction based on input
movement = new Vector2(horizontalInput, verticalInput);
// Optionally rotate the player based on movement direction
RotatePlayer(horizontalInput, verticalInput);
}
else
{
// Determine the priority of movement based on input
if (horizontalInput != 0)
{
isMovingHorizontally = true;
}
else if (verticalInput != 0)
{
isMovingHorizontally = false;
}
// Set movement direction and optionally rotate the player
if (isMovingHorizontally)
{
movement = new Vector2(horizontalInput, 0);
RotatePlayer(horizontalInput, 0);
}
else
{
movement = new Vector2(0, verticalInput);
RotatePlayer(0, verticalInput);
}
}
}
void FixedUpdate()
{
// Apply movement to the player in FixedUpdate for physics consistency
rb.velocity = movement * speed;
}
void RotatePlayer(float x, float y)
{
// If there is no input, do not rotate the player
if (x == 0 && y == 0) return;
// Calculate the rotation angle based on input direction
float angle = Mathf.Atan2(y, x) * Mathf.Rad2Deg;
// Apply the rotation to the player
transform.rotation = Quaternion.Euler(0, 0, angle);
}
}