浏览代码

Merge pull request #73 from MileyHollenberg/Linter

Setup automatic linting as a Github Action
/main
GitHub 4 年前
当前提交
83951a71
共有 8 个文件被更改,包括 292 次插入226 次删除
  1. 2
      UOP1_Project/Assets/Scripts/CameraManager.cs
  2. 297
      UOP1_Project/Assets/Scripts/Characters/Character.cs
  3. 111
      UOP1_Project/Assets/Scripts/Characters/Protagonist.cs
  4. 22
      UOP1_Project/Assets/Scripts/InputReader.cs
  5. 22
      UOP1_Project/Assets/Scripts/SpawnSystem.cs
  6. 38
      .editorconfig
  7. 26
      .github/workflows/linter.yml

2
UOP1_Project/Assets/Scripts/CameraManager.cs


{
public InputReader inputReader;
public Camera mainCamera;
public CinemachineFreeLook freeLookVCam;
public CinemachineFreeLook freeLookVCam;
public void SetupProtagonistVirtualCamera(Transform target)
{

297
UOP1_Project/Assets/Scripts/Characters/Character.cs


public class Character : MonoBehaviour
{
private CharacterController characterController;
private CharacterController characterController;
[Tooltip("Horizontal XZ plane speed multiplier")] public float speed = 8f;
[Tooltip("Smoothing for rotating the character to their movement direction")] public float turnSmoothTime = 0.2f;
[Tooltip("General multiplier for gravity (affects jump and freefall)")] public float gravityMultiplier = 5f;
[Tooltip("The initial upwards push when pressing jump. This is injected into verticalMovement, and gradually cancelled by gravity")] public float initialJumpForce = 10f;
[Tooltip("How long can the player hold the jump button")] public float jumpInputDuration = .4f;
[Tooltip("Represents how fast gravityContributionMultiplier will go back to 1f. The higher, the faster")] public float gravityComebackMultiplier = 15f;
[Tooltip("The maximum speed reached when falling (in units/frame)")] public float maxFallSpeed = 50f;
[Tooltip("Each frame while jumping, gravity will be multiplied by this amount in an attempt to 'cancel it' (= jump higher)")] public float gravityDivider = .6f;
[Tooltip("Adjust the friction of the slope")] public float slideFriction = 0.3f;
[Tooltip("Starting vertical movement when falling from a platform")] public float fallingVerticalMovement = -5f;
[Tooltip("Horizontal XZ plane speed multiplier")] public float speed = 8f;
[Tooltip("Smoothing for rotating the character to their movement direction")] public float turnSmoothTime = 0.2f;
[Tooltip("General multiplier for gravity (affects jump and freefall)")] public float gravityMultiplier = 5f;
[Tooltip("The initial upwards push when pressing jump. This is injected into verticalMovement, and gradually cancelled by gravity")] public float initialJumpForce = 10f;
[Tooltip("How long can the player hold the jump button")] public float jumpInputDuration = .4f;
[Tooltip("Represents how fast gravityContributionMultiplier will go back to 1f. The higher, the faster")] public float gravityComebackMultiplier = 15f;
[Tooltip("The maximum speed reached when falling (in units/frame)")] public float maxFallSpeed = 50f;
[Tooltip("Each frame while jumping, gravity will be multiplied by this amount in an attempt to 'cancel it' (= jump higher)")] public float gravityDivider = .6f;
[Tooltip("Adjust the friction of the slope")] public float slideFriction = 0.3f;
[Tooltip("Starting vertical movement when falling from a platform")] public float fallingVerticalMovement = -5f;
private float gravityContributionMultiplier = 0f; //The factor which determines how much gravity is affecting verticalMovement
private bool isJumping = false; //If true, a jump is in effect and the player is holding the jump button
private float jumpBeginTime = -Mathf.Infinity; //Time of the last jump
private float turnSmoothSpeed; //Used by Mathf.SmoothDampAngle to smoothly rotate the character to their movement direction
private float verticalMovement = 0f; //Represents how much a player will move vertically in a frame. Affected by gravity * gravityContributionMultiplier
private float currentSlope;
private Vector3 hitNormal; // ground normal
private bool shouldSlide; // Should player slide?
private Vector3 inputVector; //Initial input horizontal movement (y == 0f)
private Vector3 movementVector; //Final movement vector
private float gravityContributionMultiplier = 0f; //The factor which determines how much gravity is affecting verticalMovement
private bool isJumping = false; //If true, a jump is in effect and the player is holding the jump button
private float jumpBeginTime = -Mathf.Infinity; //Time of the last jump
private float turnSmoothSpeed; //Used by Mathf.SmoothDampAngle to smoothly rotate the character to their movement direction
private float verticalMovement = 0f; //Represents how much a player will move vertically in a frame. Affected by gravity * gravityContributionMultiplier
private float currentSlope;
private Vector3 hitNormal; // ground normal
private bool shouldSlide; // Should player slide?
private Vector3 inputVector; //Initial input horizontal movement (y == 0f)
private Vector3 movementVector; //Final movement vector
private const float ROTATION_TRESHOLD = .02f; // Used to prevent NaN result causing rotation in a non direction
private const float ROTATION_TRESHOLD = .02f; // Used to prevent NaN result causing rotation in a non direction
private void Awake()
{
characterController = GetComponent<CharacterController>();
}
private void Awake()
{
characterController = GetComponent<CharacterController>();
}
private void Update()
{
//Raises the multiplier to how much gravity will affect vertical movement when in mid-air
//This is 0f at the beginning of a jump and will raise to maximum 1f
if (!characterController.isGrounded)
{
gravityContributionMultiplier += Time.deltaTime * gravityComebackMultiplier;
}
//Reduce the influence of the gravity while holding the Jump button
if (isJumping)
{
//The player can only hold the Jump button for so long
if (Time.time >= jumpBeginTime + jumpInputDuration)
{
isJumping = false;
gravityContributionMultiplier = 1f; //Gravity influence is reset to full effect
}
else
{
gravityContributionMultiplier *= gravityDivider; //Reduce the gravity effect
}
}
//Calculate the final verticalMovement
if (!characterController.isGrounded)
{
//Less control in mid-air, conserving momentum from previous frame
movementVector = inputVector * speed;
//The character is either jumping or in freefall, so gravity will add up
gravityContributionMultiplier = Mathf.Clamp01(gravityContributionMultiplier);
verticalMovement += Physics.gravity.y * gravityMultiplier * Time.deltaTime * gravityContributionMultiplier; //Add gravity contribution
//Note that even if it's added, the above value is negative due to Physics.gravity.y
//Cap the maximum so the player doesn't reach incredible speeds when freefalling from high positions
verticalMovement = Mathf.Clamp(verticalMovement, -maxFallSpeed, 100f);
}
else
{
//Full speed ground movement
movementVector = inputVector * speed;
//Resets the verticalMovement while on the ground,
//so that regardless of whether the player landed from a high fall or not,
//if they drop off a platform they will always start with the same verticalMovement.
//-5f is a good value to make it so the player also sticks to uneven terrain/bumps without floating
if (!isJumping)
{
verticalMovement = fallingVerticalMovement;
gravityContributionMultiplier = 0f;
}
}
UpdateSlide();
//Apply the result and move the character in space
movementVector.y = verticalMovement;
characterController.Move(movementVector * Time.deltaTime);
//Rotate to the movement direction
movementVector.y = 0f;
if (movementVector.sqrMagnitude >= ROTATION_TRESHOLD)
{
float targetRotation = Mathf.Atan2(movementVector.x, movementVector.z) * Mathf.Rad2Deg;
transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(
transform.eulerAngles.y,
targetRotation,
ref turnSmoothSpeed,
turnSmoothTime);
}
}
private void Update()
{
//Raises the multiplier to how much gravity will affect vertical movement when in mid-air
//This is 0f at the beginning of a jump and will raise to maximum 1f
if (!characterController.isGrounded)
{
gravityContributionMultiplier += Time.deltaTime * gravityComebackMultiplier;
}
//Reduce the influence of the gravity while holding the Jump button
if (isJumping)
{
//The player can only hold the Jump button for so long
if (Time.time >= jumpBeginTime + jumpInputDuration)
{
isJumping = false;
gravityContributionMultiplier = 1f; //Gravity influence is reset to full effect
}
else
{
gravityContributionMultiplier *= gravityDivider; //Reduce the gravity effect
}
}
//Calculate the final verticalMovement
if (!characterController.isGrounded)
{
//Less control in mid-air, conserving momentum from previous frame
movementVector = inputVector * speed;
//The character is either jumping or in freefall, so gravity will add up
gravityContributionMultiplier = Mathf.Clamp01(gravityContributionMultiplier);
verticalMovement += Physics.gravity.y * gravityMultiplier * Time.deltaTime * gravityContributionMultiplier; //Add gravity contribution
//Note that even if it's added, the above value is negative due to Physics.gravity.y
//Cap the maximum so the player doesn't reach incredible speeds when freefalling from high positions
verticalMovement = Mathf.Clamp(verticalMovement, -maxFallSpeed, 100f);
}
else
{
//Full speed ground movement
movementVector = inputVector * speed;
//Resets the verticalMovement while on the ground,
//so that regardless of whether the player landed from a high fall or not,
//if they drop off a platform they will always start with the same verticalMovement.
//-5f is a good value to make it so the player also sticks to uneven terrain/bumps without floating
if (!isJumping)
{
verticalMovement = fallingVerticalMovement;
gravityContributionMultiplier = 0f;
}
}
UpdateSlide();
//Apply the result and move the character in space
movementVector.y = verticalMovement;
characterController.Move(movementVector * Time.deltaTime);
//Rotate to the movement direction
movementVector.y = 0f;
if (movementVector.sqrMagnitude >= ROTATION_TRESHOLD)
{
float targetRotation = Mathf.Atan2(movementVector.x, movementVector.z) * Mathf.Rad2Deg;
transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(
transform.eulerAngles.y,
targetRotation,
ref turnSmoothSpeed,
turnSmoothTime);
}
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
hitNormal = hit.normal;
bool isMovingUpwards = verticalMovement > 0f;
if (isMovingUpwards)
{
// Making sure the collision is near the top of the head
float permittedDistance = characterController.radius / 2f;
float topPositionY = transform.position.y + characterController.height;
float distance = Mathf.Abs(hit.point.y - topPositionY);
if (distance <= permittedDistance)
{
// Stopping any upwards movement
// and having the player fall back down
isJumping = false;
gravityContributionMultiplier = 1f;
verticalMovement = 0f;
}
}
}
//---- COMMANDS ISSUED BY OTHER SCRIPTS ----
public void Move(Vector3 movement)
{
inputVector = movement;
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
hitNormal = hit.normal;
bool isMovingUpwards = verticalMovement > 0f;
if (isMovingUpwards)
{
// Making sure the collision is near the top of the head
float permittedDistance = characterController.radius / 2f;
float topPositionY = transform.position.y + characterController.height;
float distance = Mathf.Abs(hit.point.y - topPositionY);
if (distance <= permittedDistance)
{
// Stopping any upwards movement
// and having the player fall back down
isJumping = false;
gravityContributionMultiplier = 1f;
verticalMovement = 0f;
}
}
}
//---- COMMANDS ISSUED BY OTHER SCRIPTS ----
public void Move(Vector3 movement)
{
inputVector = movement;
}
public void Jump()
{
// Disable jumping if player has to slide
if (characterController.isGrounded && !shouldSlide)
{
isJumping = true;
jumpBeginTime = Time.time;
verticalMovement = initialJumpForce; //This is the only place where verticalMovement is set to a positive value
gravityContributionMultiplier = 0f;
}
}
public void Jump()
{
// Disable jumping if player has to slide
if (characterController.isGrounded && !shouldSlide)
{
isJumping = true;
jumpBeginTime = Time.time;
verticalMovement = initialJumpForce; //This is the only place where verticalMovement is set to a positive value
gravityContributionMultiplier = 0f;
}
}
public void CancelJump()
{
isJumping = false; //This will stop the reduction to the gravity, which will then quickly pull down the character
}
public void CancelJump()
{
isJumping = false; //This will stop the reduction to the gravity, which will then quickly pull down the character
}
private void UpdateSlide()
{
// if player has to slide then add sideways speed to make it go down
if (shouldSlide)
{
movementVector.x += (1f - hitNormal.y) * hitNormal.x * (speed - slideFriction);
movementVector.z += (1f - hitNormal.y) * hitNormal.z * (speed - slideFriction);
}
// check if the controller is grounded and above slope limit
// if player is grounded and above slope limit
// player has to slide
if (characterController.isGrounded)
{
currentSlope = Vector3.Angle(Vector3.up, hitNormal);
shouldSlide = currentSlope >= characterController.slopeLimit;
}
}
private void UpdateSlide()
{
// if player has to slide then add sideways speed to make it go down
if (shouldSlide)
{
movementVector.x += (1f - hitNormal.y) * hitNormal.x * (speed - slideFriction);
movementVector.z += (1f - hitNormal.y) * hitNormal.z * (speed - slideFriction);
}
// check if the controller is grounded and above slope limit
// if player is grounded and above slope limit
// player has to slide
if (characterController.isGrounded)
{
currentSlope = Vector3.Angle(Vector3.up, hitNormal);
shouldSlide = currentSlope >= characterController.slopeLimit;
}
}

111
UOP1_Project/Assets/Scripts/Characters/Protagonist.cs


public class Protagonist : MonoBehaviour
{
public InputReader inputReader;
public Transform gameplayCamera;
public InputReader inputReader;
public Transform gameplayCamera;
private Character charScript;
private Vector2 previousMovementInput;
private bool controlsEnabled = true;
private Character charScript;
private Vector2 previousMovementInput;
private bool controlsEnabled = true;
private void Awake()
{
charScript = GetComponent<Character>();
}
private void Awake()
{
charScript = GetComponent<Character>();
}
//Adds listeners for events being triggered in the InputReader script
private void OnEnable()
{
inputReader.jumpEvent += OnJumpInitiated;
inputReader.jumpCanceledEvent += OnJumpCanceled;
inputReader.moveEvent += OnMove;
//...
}
//Adds listeners for events being triggered in the InputReader script
private void OnEnable()
{
inputReader.jumpEvent += OnJumpInitiated;
inputReader.jumpCanceledEvent += OnJumpCanceled;
inputReader.moveEvent += OnMove;
//...
}
//Removes all listeners to the events coming from the InputReader script
private void OnDisable()
{
inputReader.jumpEvent -= OnJumpInitiated;
inputReader.jumpCanceledEvent -= OnJumpCanceled;
inputReader.moveEvent -= OnMove;
//...
}
//Removes all listeners to the events coming from the InputReader script
private void OnDisable()
{
inputReader.jumpEvent -= OnJumpInitiated;
inputReader.jumpCanceledEvent -= OnJumpCanceled;
inputReader.moveEvent -= OnMove;
//...
}
private void Update()
{
RecalculateMovement();
}
private void Update()
{
RecalculateMovement();
}
private void RecalculateMovement()
{
//Get the two axes from the camera and flatten them on the XZ plane
Vector3 cameraForward = gameplayCamera.forward;
cameraForward.y = 0f;
Vector3 cameraRight = gameplayCamera.right;
cameraRight.y = 0f;
private void RecalculateMovement()
{
//Get the two axes from the camera and flatten them on the XZ plane
Vector3 cameraForward = gameplayCamera.forward;
cameraForward.y = 0f;
Vector3 cameraRight = gameplayCamera.right;
cameraRight.y = 0f;
//Use the two axes, modulated by the corresponding inputs, and construct the final vector
Vector3 adjustedMovement = cameraRight.normalized * previousMovementInput.x +
cameraForward.normalized * previousMovementInput.y;
//Use the two axes, modulated by the corresponding inputs, and construct the final vector
Vector3 adjustedMovement = cameraRight.normalized * previousMovementInput.x +
cameraForward.normalized * previousMovementInput.y;
charScript.Move(Vector3.ClampMagnitude(adjustedMovement, 1f));
}
charScript.Move(Vector3.ClampMagnitude(adjustedMovement, 1f));
}
//---- EVENT LISTENERS ----
//---- EVENT LISTENERS ----
private void OnMove(Vector2 movement)
{
if (controlsEnabled) previousMovementInput = movement;
}
private void OnMove(Vector2 movement)
{
if (controlsEnabled)
previousMovementInput = movement;
}
private void OnJumpInitiated()
{
if (controlsEnabled) charScript.Jump();
}
private void OnJumpInitiated()
{
if (controlsEnabled)
charScript.Jump();
}
private void OnJumpCanceled()
{
if (controlsEnabled) charScript.CancelJump();
}
private void OnJumpCanceled()
{
if (controlsEnabled)
charScript.CancelJump();
}
}

22
UOP1_Project/Assets/Scripts/InputReader.cs


using UnityEngine.InputSystem;
using UnityEngine.Events;
[CreateAssetMenu( fileName="Input Reader" , menuName="Game/Input Reader" )]
[CreateAssetMenu(fileName = "Input Reader", menuName = "Game/Input Reader")]
public class InputReader : ScriptableObject, GameInput.IGameplayActions
{
public UnityAction jumpEvent;

public UnityAction<Vector2> cameraMoveEvent;
GameInput gameInput;
if(gameInput == null)
if (gameInput == null)
{
gameInput = new GameInput();
gameInput.Gameplay.SetCallbacks(this);

public void OnAttack(InputAction.CallbackContext context)
{
if(attackEvent != null
if (attackEvent != null
&& context.phase == InputActionPhase.Started)
attackEvent.Invoke();
}

if(extraActionEvent != null
if (extraActionEvent != null
&& context.phase == InputActionPhase.Started)
extraActionEvent.Invoke();
}

if(interactEvent != null
if (interactEvent != null
&& context.phase == InputActionPhase.Started)
interactEvent.Invoke();
}

if(jumpEvent != null
if (jumpEvent != null
if(jumpCanceledEvent != null
if (jumpCanceledEvent != null
&& context.phase == InputActionPhase.Canceled)
jumpCanceledEvent.Invoke();
}

if(moveEvent != null)
if (moveEvent != null)
{
moveEvent.Invoke(context.ReadValue<Vector2>());
}

{
if(pauseEvent != null
if (pauseEvent != null
&& context.phase == InputActionPhase.Started)
pauseEvent.Invoke();
}

if(cameraMoveEvent != null)
if (cameraMoveEvent != null)
{
cameraMoveEvent.Invoke(context.ReadValue<Vector2>());
}

22
UOP1_Project/Assets/Scripts/SpawnSystem.cs


void Awake()
{
try
{
Spawn(_defaultSpawnIndex);
}
catch (Exception e)
{
Debug.LogError($"[SpawnSystem] Failed to spawn player. {e.Message}");
}
}
try
{
Spawn(_defaultSpawnIndex);
}
catch (Exception e)
{
Debug.LogError($"[SpawnSystem] Failed to spawn player. {e.Message}");
}
}
void Reset()
{

[ContextMenu("Attempt Auto Fill")]
private void AutoFill()
{
if(_cameraManager == null)
if (_cameraManager == null)
_cameraManager = FindObjectOfType<CameraManager>();
if (_spawnLocations == null || _spawnLocations.Length == 0)

player.gameplayCamera = _cameraManager.mainCamera.transform;
_cameraManager.SetupProtagonistVirtualCamera(player.transform);
}
}
}

38
.editorconfig


[*.cs]
indent_style = tab
indent_size = tab
indent_with_tabs = 2
align_with_tabs = true
align_keep_tabs = true
insert_final_newline = true
trim_trailing_whitespace = true
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_between_query_expression_clauses = true
csharp_indent_case_contents = true
csharp_indent_switch_labels = true
csharp_indent_case_contents_when_block = false
csharp_space_around_binary_operators = before_and_after
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_after_cast = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_after_comma = true
csharp_space_before_comma = false
csharp_space_after_dot = false
csharp_space_before_dot = false
csharp_space_after_semicolon_in_for_statement = true
csharp_space_before_semicolon_in_for_statement = false
csharp_space_around_declaration_statements = false
csharp_space_before_open_square_brackets = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_square_brackets = false
csharp_preserve_single_line_statements = false
csharp_preserve_single_line_blocks = true
csharp_using_directive_placement = outside_namespace

26
.github/workflows/linter.yml


name: Linter
# Run this workflow every time a new commit pushed to your repository
on: push
jobs:
# Set the job key. The key is displayed as the job name
# when a job name is not provided
super-lint:
# Name the Job
name: Lint code base
# Set the type of machine to run on
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: git pull
- run: dotnet tool install -g dotnet-format
- run: dotnet-format -f UOP1_Project/Assets/Scripts -v d
- name: Commit changes
uses: EndBug/add-and-commit@v5
with:
message: "[Bot] Automated dotnet-format update"
add: "*.cs"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
正在加载...
取消
保存