-
Notifications
You must be signed in to change notification settings - Fork 0
/
Player.cs
84 lines (70 loc) · 2.03 KB
/
Player.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
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
79
80
81
82
83
84
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour
{
public float floorYCord;
readonly private float _horizontalSpeed = 6f;
public bool playerMovement = false;
private Rigidbody2D _rigidBody;
readonly private float _velocity = 10;
private bool _canJump = true;
void Start()
{
_rigidBody = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (playerMovement)
{
Movement();
}
// after jump when touches ground
if (!_canJump && transform.position.y < floorYCord)
{
_canJump = true;
_rigidBody.gravityScale = 0;
_rigidBody.velocity = new Vector2(0, 0);
transform.position = new Vector3(transform.position.x, floorYCord, 0);
}
}
private void Movement()
{
float horizontalInput = Input.GetAxis("Horizontal");
// check for boundaries
if (transform.position.x < -7.5f)
{
if (horizontalInput < 0)
{
horizontalInput = 0;
}
}
else if (transform.position.x > 7.5f)
{
if (horizontalInput > 0)
{
horizontalInput = 0;
}
}
// flip the sprite if in opposite direction
if (horizontalInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
}
else if (horizontalInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
horizontalInput *= -1;
}
transform.Translate(Vector3.right * _horizontalSpeed * horizontalInput * Time.deltaTime);
// jump
if (_canJump && (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)))
{
_rigidBody.gravityScale = 2.75f;
_canJump = false;
_rigidBody.velocity = new Vector2(0, _velocity);
}
}
}