-
Notifications
You must be signed in to change notification settings - Fork 0
/
KeyboardMover.cs
48 lines (39 loc) · 1.4 KB
/
KeyboardMover.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* This component responsible for the movement of the player and the jump.
* taken from unit Documentation https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
* and modify by Yarin Shapira
*/
public class KeyboardMover : MonoBehaviour
{
[SerializeField] float playerSpeed = 2.0f;
[SerializeField] float jumpHeight = 1.0f;
[SerializeField] float gravityValue = -9.81f;
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
private void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
move = transform.TransformDirection(move);
controller.Move(move * Time.deltaTime * playerSpeed);
// Changes the height position of the player.
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
}