Wallrun Updates

-WallRunItem made for equipping/unequipping wall run
-Added Method to PlayerInventory for trying to add special items as items
-Added better method for checking if player isGrounded to PlayerMovement
-Added a setup file for preconfiguring player loadouts
-Added complex wallrun file as a work in progress to allow for robust polished wallrun mechanic
This commit is contained in:
wheatv3015
2021-10-11 10:25:52 -05:00
parent 576f5aafdf
commit 61980f55cf
9 changed files with 506 additions and 45 deletions

View File

@@ -0,0 +1,15 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WallRunItem : Item
{
public void Equip(PlayerStats p){
p.HasWallrun = true;
}
public void Unequip(PlayerStats p)
{
p.HasWallrun = false;
}
}

View File

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

View File

@@ -12,6 +12,14 @@ public class PlayerInventory : MonoBehaviour
return true;
}
public bool AddSpecialItem<T>(T itemCandidate) { // Unless we don't want the four special items to be handled by inventory/inventory manager?
if (itemCandidate is Item) {
items.Add(itemCandidate as Item);
}
return true;
}
public bool RemoveItem(Item item){
if(items.Remove(item)){
return true;

View File

@@ -30,16 +30,17 @@ public class PlayerMovement : MonoBehaviour
Vector3 impact = Vector3.zero;
//Wallrunning
public float minimumWallrunningHeight = 1.75f;
public float maximumDistanceToWall = 0.75f;
private Vector3[] directions = new Vector3[]{
Vector3.right,
Vector3.right+Vector3.forward,
Vector3.forward,
Vector3.left+Vector3.forward,
Vector3.left
};
private WallRun wallRun;
//Ground Check
public bool isGrounded { get; private set; } //Better custom is grounded
public float groundCheckDistance = 0.05f; //how far away from the ground to not be considered grounded
private float lastTimeJumped = 0f; //Last time the player jumped
const float jumpGroundingPreventionTime = 0.2f; // delay in checking if we are grounded after a jump
const float groundCheckDistanceInAir = 0.07f; //How close we have to get to ground to start checking for grounded again
public LayerMask groundCheckLayers = -1; //Physics layers checked to consider the player grounded
//Camera Variables
private Vector3 camRotation;
private Transform cam;
@@ -73,6 +74,9 @@ public class PlayerMovement : MonoBehaviour
//camera transform
cam = Camera.main.transform;
Cam = Camera.main; //RENAME WHEN CLEANING UP BLINK
//Wallrun
wallRun = gameObject.GetComponent<WallRun>();
}
void Start(){
@@ -104,6 +108,8 @@ public class PlayerMovement : MonoBehaviour
//Reads inputs and moves player
private void InputController(){
//Check if player is grounded before each frame
GroundCheck();
//Keyboard inputs
//Checks if movement keys have been pressed and calculates correct vector
@@ -115,21 +121,18 @@ public class PlayerMovement : MonoBehaviour
vel = moveX + moveZ;
//Gravity
vel.y -= pStats.PlayerGrav * Time.deltaTime;
Gravity();
driftVel = Vector3.Lerp(driftVel, vel, pStats.Traction*Time.deltaTime);
//Jump Function
Jump();
//Gravity
vel.y -= Gravity();
moveController.Move(driftVel);
}
//Calculates speed current player needs to be going
private float PlayerSpeed(){
public float PlayerSpeed(){
//If nothing is pressed speed is 0
if(Input.GetAxis("Vertical") == 0.0f && Input.GetAxis("Horizontal") == 0.0f){
pStats.CurVel = 0.0f;
@@ -167,7 +170,9 @@ public class PlayerMovement : MonoBehaviour
curJumpNum++;
jumpPressed = true;
}
lastTimeJumped = Time.time;
//NEEDS TO BE MASSIVELY CHANGE LIKELY USE RAYCAST TO CHECK IF ACTUALLY ON GROUND
//CANNOT USE CHARACTERCONTROLLER.ISGROUNDED IT IS UNRELIABLE
//If grounded no jumps have been used
@@ -177,7 +182,22 @@ public class PlayerMovement : MonoBehaviour
if(Input.GetAxis("Jump")==0) jumpPressed = false;
}
public bool GetJumpPressed() {
return jumpPressed;
}
public Camera GetPlayerCamera() {
return Cam;
}
public void AddPlayerVelocity(Vector3 additiveVelocity) {
vel += additiveVelocity;
}
public void SetPlayerVelocity(Vector3 newVelocity)
{
vel = newVelocity;
}
//Camera
private void Rotate()
@@ -201,32 +221,61 @@ public class PlayerMovement : MonoBehaviour
}
//Gravity Function for adjusting y-vel due to wallrun/glide/etc
private float Gravity(){
private void Gravity(){
//Normal Gravity
vel.y -= pStats.PlayerGrav * Time.deltaTime;
//Wallrunning
if (!moveController.isGrounded && Input.GetAxisRaw("Vertical") != 0) { //If in the air, and moving forward
RaycastHit hit;
Physics.Raycast(moveController.transform.position, Vector3.down, out hit);
if (hit.distance > minimumWallrunningHeight) //If distance from player to ground is > min ground height
{
foreach (Vector3 direction in directions)
{ //For each direction we can wallrun in
Ray ray = new Ray(moveController.transform.position, direction); //Cast a Ray to see if we are by a wall
if (Physics.Raycast(ray, out hit, maximumDistanceToWall)) //If the ray hits a wallrun wall
{
if (hit.collider.tag == "WallRun")
{
return 0; //Don't fall down
}
}
}
}
}
if (pStats.HasWallrun) { wallRun.WallRunRoutine(); } //adjusted later if we are wallrunning
//If gliding
//Go down slowly
//Else normal gravity
return pStats.PlayerGrav * Time.deltaTime;
}
void GroundCheck()
{
// Make sure that the ground check distance while already in air is very small, to prevent suddenly snapping to ground
float chosenGroundCheckDistance = isGrounded ? (moveController.skinWidth + groundCheckDistance) : groundCheckDistanceInAir;
// reset values before the ground check
isGrounded = false;
Vector3 groundNormal = Vector3.up;
// only try to detect ground if it's been a short amount of time since last jump; otherwise we may snap to the ground instantly after we try jumping
if (Time.time >= lastTimeJumped + jumpGroundingPreventionTime)
{
// if we're grounded, collect info about the ground normal with a downward capsule cast representing our character capsule
if (Physics.CapsuleCast(GetCapsuleBottomHemisphere(), GetCapsuleTopHemisphere(moveController.height), moveController.radius, Vector3.down, out RaycastHit hit, chosenGroundCheckDistance, groundCheckLayers, QueryTriggerInteraction.Ignore))
{
// storing the upward direction for the surface found
groundNormal = hit.normal;
// Only consider this a valid ground hit if the ground normal goes in the same direction as the character up
// and if the slope angle is lower than the character controller's limit
if (Vector3.Dot(hit.normal, transform.up) > 0f && IsNormalUnderSlopeLimit(groundNormal))
{
isGrounded = true;
// handle snapping to the ground
if (hit.distance > moveController.skinWidth)
{
moveController.Move(Vector3.down * hit.distance);
}
}
}
}
}
private bool IsNormalUnderSlopeLimit(Vector3 normal){ // Returns true if the slope angle represented by the given normal is under the slope angle limit of the character controller
return Vector3.Angle(transform.up, normal) <= moveController.slopeLimit;
}
private Vector3 GetCapsuleBottomHemisphere(){ // Gets the center point of the bottom hemisphere of the character controller capsule
return transform.position + (transform.up * moveController.radius);
}
private Vector3 GetCapsuleTopHemisphere(float atHeight){ // Gets the center point of the top hemisphere of the character controller capsule
return transform.position + (transform.up * (atHeight - moveController.radius));
}
//ADJUST SO DISTANCE IS DETERMINED BY SCROLL WHEEL
//blinks the player forwards

View File

@@ -0,0 +1,18 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Setup : MonoBehaviour
{
private PlayerStats pstats;
public bool hasWallRun;
[Range( 1, 50)]
public float maxSpeed;
// Start is called before the first frame update
void Start()
{
pstats = this.gameObject.GetComponent<PlayerStats>();
pstats.HasWallrun = hasWallRun;
pstats.MaxVel = maxSpeed;
}
}

View File

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

View File

@@ -0,0 +1,189 @@
using UnityEngine;
using System.Linq;
using UnityEngine.Rendering;
[RequireComponent (typeof(PlayerMovement))]
public class WallRun : MonoBehaviour
{
public float wallMaxDistance = 1;
public float wallSpeedMultiplier = 1.2f;
public float minimumHeight = 1.2f;
public float maxAngleRoll = 20;
[Range(0.0f, 1.0f)]
public float normalizedAngleThreshold = 0.1f;
public float jumpDuration = 1;
public float wallBouncing = 3;
public float cameraTransitionDuration = 1;
public float wallGravityDownForce = 20f;
[Space]
PlayerMovement playerMovementController;
Vector3[] directions;
RaycastHit[] hits;
bool isWallRunning = false;
Vector3 lastWallPosition;
Vector3 lastWallNormal;
float elapsedTimeSinceJump = 0;
float elapsedTimeSinceWallAttach = 0;
float elapsedTimeSinceWallDetatch = 0;
bool jumping;
bool isPlayergrounded() => playerMovementController.isGrounded;
public bool IsWallRunning() => isWallRunning;
bool CanWallRun()
{
float verticalAxis = Input.GetAxisRaw("Vertical");
return !isPlayergrounded() && verticalAxis > 0 && VerticalCheck();
}
bool VerticalCheck()
{
return !Physics.Raycast(transform.position, Vector3.down, minimumHeight);
}
void Start()
{
playerMovementController = GetComponent<PlayerMovement>();
directions = new Vector3[]{
Vector3.right,
Vector3.right + Vector3.forward,
Vector3.forward,
Vector3.left + Vector3.forward,
Vector3.left
};
}
public void WallRunRoutine()
{
isWallRunning = false;
if(playerMovementController.GetJumpPressed())
{
jumping = true;
}
if(CanAttach())
{
hits = new RaycastHit[directions.Length];
for(int i=0; i<directions.Length; i++)
{
Vector3 dir = transform.TransformDirection(directions[i]);
Physics.Raycast(transform.position, dir, out hits[i], wallMaxDistance);
if(hits[i].collider != null)
{
Debug.DrawRay(transform.position, dir * hits[i].distance, Color.green);
}
else
{
Debug.DrawRay(transform.position, dir * wallMaxDistance, Color.red);
}
}
if(CanWallRun())
{
hits = hits.ToList().Where(h => h.collider != null).OrderBy(h => h.distance).ToArray();
if(hits.Length > 0)
{
if(hits[0].collider.tag == "WallRun")
{
OnWall(hits[0]);
lastWallPosition = hits[0].point;
lastWallNormal = hits[0].normal;
}
}
}
}
if(isWallRunning)
{
elapsedTimeSinceWallDetatch = 0;
elapsedTimeSinceWallAttach += Time.deltaTime;
playerMovementController.AddPlayerVelocity((Vector3.down * wallGravityDownForce * Time.deltaTime));
}
else
{
elapsedTimeSinceWallAttach = 0;
elapsedTimeSinceWallDetatch += Time.deltaTime;
}
}
bool CanAttach()
{
if(jumping)
{
elapsedTimeSinceJump += Time.deltaTime;
if(elapsedTimeSinceJump > jumpDuration)
{
elapsedTimeSinceJump = 0;
jumping = false;
}
return false;
}
return true;
}
void OnWall(RaycastHit hit){
float d = Vector3.Dot(hit.normal, Vector3.up);
if(d >= -normalizedAngleThreshold && d <= normalizedAngleThreshold)
{
// Vector3 alongWall = Vector3.Cross(hit.normal, Vector3.up);
float vertical = Input.GetAxisRaw("Vertical");
Vector3 alongWall = transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position, alongWall.normalized * 10, Color.green);
Debug.DrawRay(transform.position, lastWallNormal * 10, Color.magenta);
Vector3 moveToSet = alongWall * vertical * playerMovementController.PlayerSpeed() *Time.deltaTime;// * wallSpeedMultiplier;
moveToSet.y = 0;
playerMovementController.SetPlayerVelocity(moveToSet);
Debug.Log("On Wall");
isWallRunning = true;
}
}
float CalculateSide()
{
if(isWallRunning)
{
Vector3 heading = lastWallPosition - transform.position;
Vector3 perp = Vector3.Cross(transform.forward, heading);
float dir = Vector3.Dot(perp, transform.up);
return dir;
}
return 0;
}
public float GetCameraRoll() //Cause camera to roll when wall running - call to this is player movement
{
float dir = CalculateSide();
float cameraAngle = playerMovementController.GetPlayerCamera().transform.eulerAngles.z;
float targetAngle = 0;
if(dir != 0)
{
targetAngle = Mathf.Sign(dir) * maxAngleRoll;
}
return Mathf.LerpAngle(cameraAngle, targetAngle, Mathf.Max(elapsedTimeSinceWallAttach, elapsedTimeSinceWallDetatch) / cameraTransitionDuration);
}
public Vector3 GetWallJumpDirection() //Add call in jump where if we are wallrunning and jump, the jump vector is multiplied by this
{
if(isWallRunning)
{
return lastWallNormal * wallBouncing + Vector3.up;
}
return Vector3.zero;
}
}

View File

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