The fucking 3rd time i had to upload this project to git

This commit is contained in:
Madhav Kapa
2023-10-06 20:18:29 -04:00
commit 5658acfe16
2689 changed files with 1259400 additions and 0 deletions

BIN
Assets/Scripts/Player/.DS_Store vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c1aca789321cc19488a218ef5028c73b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,28 @@
using UnityEngine;
namespace Player.Information
{
public class PlayerDialogue : MonoBehaviour
{
public GameObject dialogueMaster;
private GameObject chatHolder;
private GameObject chatPrompt;
private void Start()
{
chatHolder = dialogueMaster.transform.Find("Chat Holder").gameObject;
chatPrompt = dialogueMaster.transform.Find("Chat Prompt").gameObject;
chatHolder.SetActive(false);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.LeftAlt))
{
chatHolder.SetActive(!chatHolder.activeSelf);
chatPrompt.SetActive(!chatPrompt.activeSelf);
}
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: dc09d3a52bf3249bca6ecf5691ea62e9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,154 @@
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using Player.Movement;
namespace Player.Information
{
public class PlayerStats : MonoBehaviour
{
[SerializeField] private float maxHealth = 100;
[SerializeField] private float healthDepleteRate = 1;
[SerializeField] private float maxHunger = 20f;
[SerializeField] private float maxHydration = 10f;
[SerializeField] private int nanites = 10;
[SerializeField] private Transform spawnpoint;
[SerializeField] public bool jetpackEnabled;
[SerializeField] public bool inputEnabled = true;
public bool grappleEnabled;
private float health;
private Image healthContent;
private float hunger;
private Image hungerContent;
private float hydration;
private Image hydrationContent;
private TMP_Text naniteContent;
private PlayerPhysics playerPhysics;
private GameObject statUI;
private Image thrustContent;
// Start is called before the first frame update
private void Start()
{
health = maxHealth;
hunger = maxHunger;
hydration = maxHydration;
statUI = GameObject.Find("Survival Stats");
healthContent = statUI.transform.Find("Health Bar/Health Value").gameObject.GetComponent<Image>();
hungerContent = statUI.transform.Find("Hunger Bar/Hunger Value").gameObject.GetComponent<Image>();
hydrationContent = statUI.transform.Find("Hydration Bar/Hydration Value").gameObject.GetComponent<Image>();
naniteContent = statUI.transform.Find("Nanite Bar").gameObject.GetComponent<TMP_Text>();
thrustContent = statUI.transform.Find("Thrust Bar/Thrust Value").gameObject.GetComponent<Image>();
SetNanites(nanites);
playerPhysics = gameObject.GetComponent<PlayerPhysics>();
}
// Update is called once per frame
private void Update()
{
TickStats();
}
//called each frame to update stat values
public void TickStats()
{
TickHunger();
TickHydration();
if (hunger == 0f || hydration == 0f) ChangeHealth(-healthDepleteRate * Time.deltaTime);
if (health == 0)
{
Debug.Log("player died");
Respawn();
}
}
public void ChangeStat(ref float stat, float maxStat, float change, ref Image statContent)
{
stat = Mathf.Clamp(stat + change, 0f, maxStat);
statContent.fillAmount = Mathf.Clamp(stat / maxStat, 0f, 1f);
}
public void TickHunger()
{
ChangeHunger(-Time.deltaTime);
}
public void TickHydration()
{
ChangeHydration(-Time.deltaTime);
}
public void ChangeHealth(float change)
{
ChangeStat(ref health, maxHealth, change, ref healthContent);
}
public void ChangeHunger(float change)
{
ChangeStat(ref hunger, maxHunger, change, ref hungerContent);
}
public void ChangeHydration(float change)
{
ChangeStat(ref hydration, maxHydration, change, ref hydrationContent);
}
public void ConsumeResource(float change, string name)
{
if (name == "Food")
ChangeHunger(change);
else if (name == "Water")
ChangeHydration(change);
else if (name == "Health") ChangeHealth(change);
}
public int GetNanites()
{
return nanites;
}
public void SetNanites(int s)
{
nanites = s;
naniteContent.SetText(nanites.ToString());
}
public void ChangeNanites(int c)
{
SetNanites(nanites + c);
}
public void Respawn()
{
// Note, this respawn script will have to be more advanced in later versions.
ChangeHealth(maxHealth);
ChangeHunger(maxHunger);
ChangeHydration(maxHydration);
transform.position = spawnpoint.position;
transform.rotation = spawnpoint.rotation;
playerPhysics.Reset();
}
public void SetThrust(float amount)
{
thrustContent.fillAmount = amount;
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b0d818a45884a4068a5ac6a6cbdb184e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: aa3116809fe12c44594680a2846a99e9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,53 @@
using UnityEngine;
namespace Player.Interactions
{
public class ConstructMenuItem
{
private readonly string desc;
private readonly Sprite image;
private readonly string name;
private readonly GameObject target;
public ConstructMenuItem(string name, Sprite image, string desc)
{
this.name = name;
this.image = image;
this.desc = desc;
target = null;
}
public ConstructMenuItem(string name, Sprite image, string desc, GameObject target)
{
this.name = name;
this.image = image;
int cost = target.GetComponent<ConstructBase>().GetCost();
if (cost == 1)
this.desc = desc + "\nCosts " + cost + " Nanite.";
else
this.desc = desc + "\nCosts " + cost + " Nanites.";
this.target = target;
}
public string GetName()
{
return name;
}
public Sprite GetImage()
{
return image;
}
public string GetDesc()
{
return desc;
}
public GameObject GetTarget()
{
return target;
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c019fe381690348c59444c8294aa15d7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,100 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using Player.Information;
namespace Player.Interactions
{
public class ConstructSelector : MonoBehaviour
{
public GameObject foodMakerPrefab;
public GameObject player;
public Sprite foodMakerImage;
public GameObject waterMakerPrefab;
public Sprite waterMakerImage;
public GameObject healthAreaPrefab;
public Sprite healthAreaImage;
public Image constructImage;
public GameObject selectedImage;
public GameObject unselectedArrow;
private readonly List<ConstructMenuItem> choices = new();
public TMP_Text constructDesc;
public TMP_Text constructName;
private int currentIndex;
private int selectedIndex;
private PlayerStats playerStats;
// Start is called before the first frame update
private void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
playerStats = player.GetComponent<PlayerStats>();
choices.Add(new ConstructMenuItem("Nutrient Consolidator", foodMakerImage,
"Scrapes nutrients from the ground to make food.\n\nRelies on local biodensity.", foodMakerPrefab));
choices.Add(new ConstructMenuItem("Water Condenser", waterMakerImage,
"Condenses vapor from the atmosphere to make water.\n\nRelies on local humidity.", waterMakerPrefab));
choices.Add(new ConstructMenuItem("Regeneration Field", healthAreaImage,
"Distributes nanites onto organisms to repair tissue.\n\nRequires proximity.", healthAreaPrefab));
currentIndex = 0;
selectedIndex = 0;
RenderPanel();
}
// Update is called once per frame
private void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow) )
{
currentIndex--;
if (currentIndex < 0) currentIndex = choices.Count - 1;
RenderPanel();
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
currentIndex++;
if (currentIndex >= choices.Count) currentIndex = 0;
RenderPanel();
}
if (Input.GetKeyDown(KeyCode.UpArrow) )
{
selectedIndex = currentIndex;
RenderPanel();
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
}
}
public void RenderPanel()
{
constructName.SetText(choices[currentIndex].GetName());
constructImage.sprite = choices[currentIndex].GetImage();
constructDesc.SetText(choices[currentIndex].GetDesc());
if (selectedIndex == currentIndex)
{
selectedImage.SetActive(true);
unselectedArrow.SetActive(false);
}
else
{
selectedImage.SetActive(false);
unselectedArrow.SetActive(true);
}
}
public GameObject GetSelected()
{
return choices[selectedIndex].GetTarget();
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 21a3bcb112beb4f3f8aa38fc58a2c67d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,119 @@
using UnityEngine;
using Player.Information;
namespace Player.Interactions
{
public class GrappleHook : MonoBehaviour
{
[SerializeField] private float maxGrappleThrow;
[SerializeField] private float grappleStrength;
[SerializeField] public float grappledAirControl;
[SerializeField] private GameObject grapplePointPrefab;
public bool grappled;
[SerializeField] private LineRenderer lineRender;
public GameObject reticleMaster;
private GameObject curPointObj;
private Vector3 grapplePos;
private PlayerStats playerStats;
private GameObject reticleClose;
private GameObject reticleOpen;
// Start is called before the first frame update
private void Start()
{
grappled = false;
grapplePos = Vector3.zero;
lineRender.enabled = false;
reticleOpen = reticleMaster.transform.Find("Reticle Open").gameObject;
reticleClose = reticleMaster.transform.Find("Reticle Close").gameObject;
reticleClose.SetActive(false);
playerStats = gameObject.GetComponent<PlayerStats>();
}
// Update is called once per frame
private void Update()
{
if (playerStats.grappleEnabled)
{
if (WouldGrapple())
{
reticleOpen.SetActive(false);
reticleClose.SetActive(true);
}
else
{
reticleOpen.SetActive(true);
reticleClose.SetActive(false);
}
if ((Input.GetKeyDown(KeyCode.L) || Input.GetMouseButtonDown(0)) ) ShootGrapple();
if ((Input.GetKeyDown(KeyCode.K) || Input.GetMouseButtonUp(0)) ) ReleaseGrapple();
if (grappled)
{
lineRender.SetPosition(0, gameObject.transform.position);
lineRender.SetPosition(1, grapplePos);
}
}
}
public bool WouldGrapple()
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit,
maxGrappleThrow))
{
TraversalProperties tp = hit.collider.gameObject.GetComponent<TraversalProperties>();
if (tp == null || tp.canGrappleOnto) return true;
}
return false;
}
public void ShootGrapple()
{
// perform a raycast from the player's reticle
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit,
maxGrappleThrow))
{
//Debug.DrawRay(Camera.main.transform.position, hit.point, Color.green, 5f);
TraversalProperties tp = hit.collider.gameObject.GetComponent<TraversalProperties>();
if (tp == null || tp.canGrappleOnto)
{
grappled = true;
grapplePos = hit.point;
if (curPointObj != null) Destroy(curPointObj);
curPointObj = Instantiate(grapplePointPrefab, hit.point, Quaternion.identity);
lineRender.enabled = true;
}
}
}
public void ReleaseGrapple()
{
grappled = false;
grapplePos = Vector3.zero;
if (curPointObj != null) Destroy(curPointObj);
lineRender.enabled = false;
}
public Vector3 PullForce(Vector3 playerPos)
{
if (!grappled)
return Vector3.zero;
return (grapplePos - playerPos).normalized * grappleStrength;
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3e7f9353d2ac547538de04c5e5988dd0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,92 @@
using UnityEngine;
using Player.Movement;
using Player.Information;
namespace Player.Interactions
{
public class JetPack : MonoBehaviour
{
// in Newtons
[SerializeField] private float thrustStrength;
// in seconds
[SerializeField] private float maxLoftTime;
// in seconds per seconds
[SerializeField] private float loftReclaimRate;
[SerializeField] private float airLoftReclaimRate;
// particle system for jetpack
[SerializeField] private ParticleSystem flames;
private bool active;
private float loftTime;
private PlayerPhysics playerPhysics;
private PlayerStats playerStats;
private void Start()
{
SetActiveThrust(false);
loftTime = maxLoftTime;
playerPhysics = gameObject.GetComponent<PlayerPhysics>();
playerStats = gameObject.GetComponent<PlayerStats>();
}
private void Update()
{
if (playerStats.jetpackEnabled)
{
if (Input.GetKey(KeyCode.Q) )
{
if (loftTime > 0f)
{
SetActiveThrust(true);
loftTime = Mathf.Max(0f, loftTime - Time.deltaTime);
}
else
{
SetActiveThrust(false);
}
}
else
{
SetActiveThrust(false);
if (loftTime < maxLoftTime)
{
if (playerPhysics.isGrounded())
loftTime = Mathf.Min(maxLoftTime, loftTime + loftReclaimRate * Time.deltaTime);
else
loftTime = Mathf.Min(maxLoftTime, loftTime + airLoftReclaimRate * Time.deltaTime);
}
}
playerStats.SetThrust(loftTime / maxLoftTime);
}
}
public Vector3 ThrustForce()
{
if (active)
return new Vector3(0f, thrustStrength, 0f);
return Vector3.zero;
}
private void SetActiveThrust(bool state)
{
active = state;
SetEmission(state);
}
private void SetEmission(bool state)
{
var emission = flames.emission;
emission.enabled = state;
}
public void ResetThrust()
{
loftTime = maxLoftTime;
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d8d226b0302f94fd38153b488954c2b0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,117 @@
using UnityEngine;
using Player.Information;
using Player.Interactions;
public class PlayerInteractions : MonoBehaviour
{
[SerializeField] private float maxInteractDistance = 1f;
public GameObject selectionMaster;
public GameObject multiToolModel;
private ConstructSelector cs;
private PlayerStats playerStats;
private GameObject selectionHolder;
private GameObject selectionPrompt;
// Start is called before the first frame update
private void Start()
{
playerStats = gameObject.GetComponent<PlayerStats>();
//cs.gameObject.SetActive(false);
selectionHolder = selectionMaster.transform.Find("Selection Holder").gameObject;
selectionPrompt = selectionMaster.transform.Find("Selection Prompt").gameObject;
cs = selectionHolder.GetComponent<ConstructSelector>();
selectionHolder.SetActive(false);
multiToolModel.SetActive(false);
//Screen.fullScreenMode = FullScreenMode.ExclusiveFullScreen;
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
private void Update()
{
if (Input.GetKeyDown(KeyCode.R) )
{
Debug.Log("R Pressed");
InteractWithObject();
}
/*
if (Input.GetKeyDown(KeyCode.Q))
{
DisassembleObject();
}
*/
if (Input.GetKeyDown(KeyCode.E) )
{
DisassembleObject();
PlaceObject();
}
if (Input.GetKeyDown(KeyCode.Tab) )
{
selectionHolder.SetActive(!selectionHolder.activeSelf);
selectionPrompt.SetActive(!selectionPrompt.activeSelf);
multiToolModel.SetActive(!multiToolModel.activeSelf);
}
}
public void InteractWithObject()
{
RaycastHit hit;
Debug.Log("interact");
//Debug.DrawRay(Camera.main.transform.position, Camera.main.transform.forward, Color.green, 3f);
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit,
maxInteractDistance))
{
Debug.Log(hit.collider.gameObject);
//Debug.DrawRay(Camera.main.transform.position, hit.point, Color.green, 5f);
if (hit.collider.gameObject.tag == "Construct")
{
ConstructMaker maker = hit.collider.gameObject.GetComponent<ConstructMaker>();
if (maker != null)
{
float change = maker.Interact();
playerStats.ConsumeResource(change, maker.GetResource());
}
}
if (hit.collider.gameObject.tag == "Key") hit.collider.gameObject.SetActive(false);
}
}
public void DisassembleObject()
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit,
maxInteractDistance))
if (hit.collider.gameObject.tag == "Construct")
{
int reward = hit.collider.gameObject.GetComponent<ConstructBase>().Disassemble();
playerStats.ChangeNanites(reward);
}
}
public void PlaceObject()
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit,
maxInteractDistance))
if (Vector3.Normalize(hit.normal) == Vector3.up && hit.collider.gameObject.tag != "Construct")
{
GameObject selectedConstruct = cs.GetSelected();
int cost = selectedConstruct.GetComponent<ConstructBase>().GetCost();
if (cost <= playerStats.GetNanites())
{
var construct = Instantiate(selectedConstruct, hit.point + Vector3.up * 0.3f, Quaternion.identity);
playerStats.ChangeNanites(-cost);
}
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c8444a0389c8844a89130facf25837a9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 15c4dba372dd94727b6dfe262983c56f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,19 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MetaMenu : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
SceneManager.LoadScene("MainMenu");
}
if (Input.GetKeyDown(KeyCode.F))
{
Screen.fullScreen = !Screen.fullScreen;
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 41353f2b6e88a4e6b84c0c56caade718
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b6667fe3441725a458384c6b95941381
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,47 @@
using UnityEngine;
namespace Player.Movement
{
public class MouseLook : MonoBehaviour
{
[SerializeField] public float mouseSensitivity = 100f;
public float xRotation;
private Transform playerBody;
// Start is called before the first frame update
private void Start()
{
// check playerprefs for sensitivity
// if not set, set to 100
// if set, set to playerprefs
if (!PlayerPrefs.HasKey("Sensitivity"))
{
PlayerPrefs.SetFloat("Sensitivity", 100f);
}
else
{
mouseSensitivity = PlayerPrefs.GetFloat("Sensitivity");
}
playerBody = transform.parent;
Cursor.lockState = CursorLockMode.Locked;
//mouseSensitivity = PlayerPrefs.GetFloat("Sensitivity");
}
// Update is called once per frame
private void Update()
{
var mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
var mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
playerBody.Rotate(Vector3.up * mouseX);
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 867f6d1560c5c4838bf513a400b50bec
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,67 @@
using UnityEngine;
using Player.Interactions;
public class PlayerMovement : MonoBehaviour
{
// Start is called before the first frame update
private void Start()
{
_controller = gameObject.GetComponent<CharacterController>();
_moveSpeed = walkSpeed;
_sprintBonus = sprintSpeed - walkSpeed;
grappleHook = gameObject.GetComponent<GrappleHook>();
}
// Update is called once per frame
private void Update()
{
// ground check
// isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
_isGrounded = _controller.isGrounded;
if (_isGrounded && playerVelocity.y < 0) playerVelocity.y = -2f;
// sprint mechanic
var sprintInput = Input.GetAxis("Sprint");
// wasd player movement
var xMove = Input.GetAxis("Horizontal");
var zMove = Input.GetAxis("Vertical");
var xzMove = (transform.right * xMove + transform.forward * zMove) * (_moveSpeed + sprintInput * _sprintBonus);
// jump
if (Input.GetButtonDown("Jump") && _isGrounded) playerVelocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
// gravity
playerVelocity.y += gravity * Time.deltaTime;
// force applied by grapple hook
//playerVelocity += grappleHook.PullForce(transform.position) * Time.deltaTime;
// final player move
_controller.Move((playerVelocity + xzMove) * Time.deltaTime);
//Debug.Log(controller.isGrounded);
}
#region Variables
[SerializeField] private float walkSpeed = 2f;
[SerializeField] private float sprintSpeed = 10f;
private float _moveSpeed;
private float _sprintBonus;
private CharacterController _controller;
public Vector3 playerVelocity;
[SerializeField] private float jumpHeight = 2f;
[SerializeField] private float gravity = -10f;
private bool _isGrounded;
private GrappleHook grappleHook;
#endregion
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b3ecedebba2564ed7ad0bca94c48c9a0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,149 @@
using UnityEngine;
public class PlayerMovement2 : MonoBehaviour
{
// Start is called before the first frame update
private void Start()
{
controller = gameObject.GetComponent<CharacterController>();
playerVelocity = Vector3.zero;
playerAcceleration = Vector3.zero;
moveSpeed = walkSpeed;
sprintBonus = sprintSpeed - walkSpeed;
}
private void Update()
{
// acceleration of an object by default is zero
playerAcceleration = Vector3.zero;
// determine if the player is grounded
isGrounded = controller.isGrounded;
playerAcceleration += new Vector3(0f, gravity, 0f);
// add acceleration due to normal force, assuming platforms are stationary and parallel to the ground
if (isGrounded) playerAcceleration += new Vector3(0f, -gravity, 0f);
// when the player jumps on the ground, apply an instant force to the player's velocity
if (isGrounded && Input.GetButtonDown("Jump")) playerAcceleration.y += jumpHeight;
// handle force applied by player movement
if (isGrounded)
if (playerVelocity.magnitude < maxWalkSpeed)
{
//Vector3 xzMove = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
var xzMove = Vector3.zero;
if (Input.GetKey(KeyCode.W)) xzMove.z += 1f;
if (Input.GetKey(KeyCode.S)) xzMove.z += -1f;
if (Input.GetKey(KeyCode.D)) xzMove.x += 1f;
if (Input.GetKey(KeyCode.A)) xzMove.x += -1f;
xzMove = xzMove.normalized * moveSpeed;
var transformedDisplacement = transform.right * xzMove.x + transform.forward * xzMove.z;
playerAcceleration += transformedDisplacement;
}
// add acceleration due to friction
if (isGrounded)
{
var forceByFriction = Vector3.ProjectOnPlane(playerVelocity.normalized, transform.up) * frictionDefault;
playerAcceleration -= forceByFriction;
}
// add to player's velocity based on acceleartion
playerVelocity += playerAcceleration * Time.deltaTime;
/*
// assume all platforms are stationary and parallel to the ground
if (isGrounded && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
// when the player jumps on the ground, apply an instant force to the player's velocity
if (isGrounded && Input.GetButtonDown("Jump"))
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -2f * gravity);
}
// apply an instant force to the player's velocity when on the ground when they try to move
if (isGrounded)
{
if (playerVelocity.magnitude < maxWalkSpeed)
{
Vector3 xzMove = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
xzMove = xzMove.normalized * moveSpeed * Time.deltaTime;
playerVelocity += transform.right * xzMove.x + transform.forward * xzMove.z;
}
}
*/
// add to the player's position based on velocity
controller.Move(playerVelocity * Time.deltaTime);
Debug.Log(playerVelocity.magnitude);
}
#region Variables
[SerializeField] private float walkSpeed = 2f;
[SerializeField] private float maxWalkSpeed = 10f;
[SerializeField] private float sprintSpeed = 10f;
private float moveSpeed;
private float sprintBonus;
[SerializeField] private float jumpHeight = 2f;
[SerializeField] private float gravity = -10f;
[SerializeField] private float frictionDefault = 1f;
private CharacterController controller;
public Vector3 playerVelocity;
public Vector3 playerAcceleration;
private bool isGrounded;
#endregion
/*
// Update is called once per frame
void Update()
{
// ground check
// isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
isGrounded = controller.isGrounded;
if (isGrounded && playerVelocity.y < 0)
{
playerVelocity.y = -2f;
}
// sprint mechanic
float sprintInput = Input.GetAxis("Sprint");
// wasd player movement
float xMove = Input.GetAxis("Horizontal");
float zMove = Input.GetAxis("Vertical");
Vector3 xzMove = (transform.right * xMove + transform.forward * zMove) * (moveSpeed + sprintInput * sprintBonus);
// jump
if (Input.GetButtonDown("Jump") && isGrounded)
{
playerVelocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
// gravity
playerVelocity.y += gravity * Time.deltaTime;
// final player move
controller.Move((playerVelocity + xzMove) * Time.deltaTime);
//Debug.Log(controller.isGrounded);
}
*/
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e8682b16961bcd049923fff1bdc4126d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,78 @@
using UnityEngine;
using Player.Interactions;
public class PlayerMovement3 : MonoBehaviour
{
// Start is called before the first frame update
private void Start()
{
_controller = gameObject.GetComponent<CharacterController>();
_moveSpeed = walkSpeed;
_sprintBonus = sprintSpeed - walkSpeed;
grappleHook = gameObject.GetComponent<GrappleHook>();
}
// Update is called once per frame
private void Update()
{
// an object by default has no forces acting on it, and therefore, zero acceleration
playerAcceleration = Vector3.zero;
// acceleration due to gravity
playerAcceleration += new Vector3(0f, gravity, 0f);
// ground check
_isGrounded = _controller.isGrounded;
// assuming platforms are horizontal and stationary
if (_isGrounded && playerVelocity.y < 0) playerVelocity.y = -2f;
// instant force applied on jump
if (Input.GetButtonDown("Jump") && _isGrounded) playerVelocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
// sprint mechanic
var sprintInput = Input.GetAxis("Sprint");
// wasd player movement
var xMove = Input.GetAxis("Horizontal");
var zMove = Input.GetAxis("Vertical");
var transformedMove = transform.right * xMove + transform.forward * zMove;
if (transformedMove.magnitude > 1f) transformedMove = transformedMove.normalized;
var xzMove = transformedMove * (_moveSpeed + sprintInput * _sprintBonus);
// instance force applied when moving
_controller.Move(xzMove * Time.deltaTime);
// force applied by grapple hook
//playerVelocity += grappleHook.PullForce(transform.position) * Time.deltaTime;
// apply acceleration to player velocity
playerVelocity += playerAcceleration * Time.deltaTime;
// apply velocity to change position
_controller.Move(playerVelocity * Time.deltaTime);
//Debug.Log(controller.isGrounded);
}
#region Variables
[SerializeField] private float walkSpeed = 2f;
[SerializeField] private float sprintSpeed = 10f;
private float _moveSpeed;
private float _sprintBonus;
private CharacterController _controller;
public Vector3 playerAcceleration;
public Vector3 playerVelocity;
[SerializeField] private float jumpHeight = 2f;
[SerializeField] private float gravity = -10f;
private bool _isGrounded;
private GrappleHook grappleHook;
#endregion
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9c4fb8c78ea7749a3a9e88c9ae55e131
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,208 @@
using Player.Interactions;
using UnityEngine;
using Player.Information;
namespace Player.Movement
{
public class PlayerPhysics : MonoBehaviour
{
// measured in meters per second squared
[SerializeField] private Vector3 gravity;
[SerializeField] private float walkingForce;
[SerializeField] private float maxWalkSpeed;
[SerializeField] private float maxRunSpeed;
// measured in N applied when space is pressed
[SerializeField] private float jumpForce;
[SerializeField] private float defaultAirControl;
// the minimum change in speed which will result in damage being taken
[SerializeField] private float speedDamageThreshold;
// the ratio of speed change to damage taken
[SerializeField] private float speedToDamage;
// measured in seconds
[SerializeField] private float coyoteTime;
[SerializeField] private float jumpBuffer;
// current air control ratio experienced by the player
private float airControl;
private float coyoteTimeCounter;
// reference to GrappleHook script
private GrappleHook grappleHook;
// reference to JetPack script
private JetPack jetPack;
private float jumpBufferCounter;
// current maximum input speed of the player
private float maxSpeed;
// referendce to PlayerStats script
private PlayerStats playerStats;
// metrics for ground detection
//private float playerHeight;
//private Vector3 boxDim;
// speed of the player in the previous frame
private float prevFrameSpeed;
private Rigidbody rb;
public void Reset()
{
prevFrameSpeed = 0f;
rb.velocity = Vector3.zero;
grappleHook.ReleaseGrapple();
jetPack.ResetThrust();
}
// Start is called before the first frame update
private void Start()
{
rb = gameObject.GetComponent<Rigidbody>();
// ground detection constants
//playerHeight = (transform.localScale.y / 2f);
//Vector3 boxDim = transform.localScale;
//boxDim = new Vector3(boxDim.x - 0.5f, boxDim.y + 0.5f, boxDim.z - 0.5f);
maxSpeed = maxWalkSpeed;
airControl = defaultAirControl;
grappleHook = gameObject.GetComponent<GrappleHook>();
jetPack = gameObject.GetComponent<JetPack>();
playerStats = gameObject.GetComponent<PlayerStats>();
prevFrameSpeed = 0f;
}
// Update is called once per frame
private void Update()
{
var grounded = isGrounded();
// coyote time manager
if (grounded)
coyoteTimeCounter = coyoteTime;
else
coyoteTimeCounter -= Time.deltaTime;
// jump buffer manager
if (Input.GetButtonDown("Jump") )
jumpBufferCounter = jumpBuffer;
else
jumpBufferCounter -= Time.deltaTime;
//Debug.Log("Coyote: " + coyoteTimeCounter + ". Buffer: " + jumpBufferCounter);
// if jump key is pressed
if (coyoteTimeCounter > 0f && jumpBufferCounter > 0f)
{
Debug.Log("jump");
// apply an upward force to the player
rb.AddForce(new Vector3(0f, jumpForce, 0f));
coyoteTimeCounter = 0f;
jumpBufferCounter = 0f;
}
// change current max speed depending on sprinting or not
if (Input.GetKey(KeyCode.LeftShift) && grounded )
maxSpeed = maxRunSpeed;
else
maxSpeed = maxWalkSpeed;
}
private void FixedUpdate()
{
// get the input values for player movement
var movement = GetMoveInputs();
// calculate the velocity change of the player based on input
movement = movement.normalized * walkingForce;
// scale movement force if not on ground
if (!isGrounded()) movement *= airControl;
var relativeMove = transform.right * movement.x + transform.forward * movement.z;
var flatCurVelocity = Vector3.ProjectOnPlane(rb.velocity, transform.up);
// calculate the velocity the player would have when adding input velocity to it
var nextVelocity = flatCurVelocity + relativeMove * Time.deltaTime;
// check if the player's next velocity has a magnitude above walking speed
if (nextVelocity.magnitude > maxSpeed)
{
// if the player is currently moving below their maxSpeed and trying to accelerate up to it
if (flatCurVelocity.magnitude < maxSpeed)
// scale the player's next velocity to be equal to their maxSpeed
nextVelocity = nextVelocity.normalized * maxSpeed;
else
// else, scale the player's next velocity to equal their current speed
nextVelocity = nextVelocity.normalized * flatCurVelocity.magnitude;
}
// set the player's current velocity to their next velocity in the xz-plane
rb.velocity = new Vector3(nextVelocity.x, rb.velocity.y, nextVelocity.z);
// apply the force of a potential grapple hook to the player
rb.AddForce(grappleHook.PullForce(transform.position));
// apply the force of a potential jetpack to the player
rb.AddForce(jetPack.ThrustForce());
// apply the force of gravity to the player
rb.AddForce(gravity, ForceMode.Acceleration);
// calculate the change in player speed this frame
var deltaSpeed = Mathf.Abs(rb.velocity.magnitude - prevFrameSpeed);
// apply force damage to player depending on change in speed
if (deltaSpeed > speedDamageThreshold)
//Debug.Log(deltaSpeed - speedDamageThreshold);
playerStats.ChangeHealth(-speedToDamage * (deltaSpeed - speedDamageThreshold));
// update speed record for next frame
prevFrameSpeed = rb.velocity.magnitude;
//Debug.Log(isGrounded());
}
private void OnTriggerEnter(Collider other)
{
var tp = other.gameObject.GetComponent<TraversalProperties>();
if (tp != null && tp.lethalToEnter) playerStats.Respawn();
}
public Vector3 GetMoveInputs()
{
var xzMove = Vector3.zero;
if (Input.GetKey(KeyCode.W)) xzMove.z += 1f;
if (Input.GetKey(KeyCode.S)) xzMove.z += -1f;
if (Input.GetKey(KeyCode.D)) xzMove.x += 1f;
if (Input.GetKey(KeyCode.A)) xzMove.x += -1f;
return xzMove;
}
public bool isGrounded()
{
// Raycast using ray
//return Physics.Raycast(transform.position, -Vector3.up, playerHeight + 0.1f);
// Raycast using box
//Vector3 boxCenter = transform.position - new Vector3(0f, playerHeight, 0f);
//return Physics.CheckBox(boxCenter, boxDim);
// Raycast using box hardcoded
var boxCenter = transform.position - new Vector3(0f, 0.5f, 0f);
return Physics.CheckBox(boxCenter, new Vector3(0.25f, 0.52f, 0.25f));
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6371500714cc7409c92e2a14cced0fca
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: