Skip to content

Commit

Permalink
Jump Push
Browse files Browse the repository at this point in the history
Push JKump
  • Loading branch information
aps16104 committed Apr 21, 2020
1 parent 538d80a commit d8a7b16
Show file tree
Hide file tree
Showing 5 changed files with 662 additions and 356 deletions.
134 changes: 134 additions & 0 deletions Platformer/Assets/Scripts/Controller2D.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider2D))] //Require BoxCollider
public class Controller2D : MonoBehaviour
{
public LayerMask collisionMask; //Objects we collide with

const float skinWidth = .25f; //const so you cant change the value, and width
public int horizontalRayCount = 4; //Amount of rays shooting horizontally
public int verticalRayCount = 4;//Amount of rays shooting Vertically

float horizontalRaySpacing; //Spacing between each horizontal ray
float verticalRaySpacing; //Spacing between each vertical ray

BoxCollider2D collider; //Reference
RaycastOrigins raycastOrigins; //Reference to raycastorigins
public CollisionInfo collisions; //Reference to Collison Info

void Start()
{
collider = GetComponent<BoxCollider2D>();
CalculateRaySpacing(); //never changes
}

public void Move(Vector3 velocity) //Actually Moving
{
UpdateRaycastOrigins(); //Everytime we move
collisions.Reset(); //Blank Slate

if (velocity.x != 0)//Horizontal Axis
{
HorizontalCollisions(ref velocity);
}
if (velocity.y != 0) //Vertical Axis
{
VerticalCollisions(ref velocity);
}

transform.Translate(velocity); //Actually modifies the velocity
}

void HorizontalCollisions(ref Vector3 velocity) //reference to velocity vector (dont make a copy)
{
float directionX = Mathf.Sign(velocity.x); //depending on moving left or right
float rayLength = Mathf.Abs(velocity.x) + skinWidth; //length of the ray (always positve)

for (int i = 0; i < horizontalRayCount; i++)
{
Vector2 rayOrigin = (directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight;// See if moving up or down, then choose corresponding
rayOrigin += Vector2.up * (horizontalRaySpacing * i);//cast rays from where we will be once moving
RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask);//raycast from origin and have it go up, length of the ray, layer mask

Debug.DrawRay(rayOrigin, Vector2.right * directionX * rayLength, Color.red);//multiply to maintain direction

if (hit)
{
velocity.x = (hit.distance - skinWidth) * directionX; //Multiply to maintain direction
rayLength = hit.distance; //length of ray is now the distance to hit

collisions.left = directionX == -1; //if hit and going left, collison left is true
collisions.right = directionX == 1; //if hit and going right, collision right is true
}
}
}

void VerticalCollisions(ref Vector3 velocity) //reference to velocity vector (dont make a copy)
{
float directionY = Mathf.Sign(velocity.y); //depending on moving up or done
float rayLength = Mathf.Abs(velocity.y) + skinWidth; //length of the ray (always positve)

for (int i = 0; i < verticalRayCount; i++)
{
Vector2 rayOrigin = (directionY == -1) ? raycastOrigins.bottomLeft : raycastOrigins.topLeft; // See if moving up or down, then choose corresponding
rayOrigin += Vector2.right * (verticalRaySpacing * i + velocity.x); //cast rays from where we will be once moving
RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask); //raycast from origin and have it go up, length of the ray, layer mask

Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red);

if (hit) //if it hits
{
velocity.y = (hit.distance - skinWidth) * directionY; //multiply to maintain direction
rayLength = hit.distance; //length of ray is now the distance to hit
collisions.below = directionY == -1; //if hit and going down, below is true
collisions.above = directionY == 1; //if hit and going up, above is true
}
}
}



void UpdateRaycastOrigins() //Update raycast origins
{
Bounds bounds = collider.bounds; //Getting bounds from the collider
bounds.Expand(skinWidth * -2); //Shrinks

raycastOrigins.bottomLeft = new Vector2(bounds.min.x, bounds.min.y); //Bottom Left corner
raycastOrigins.bottomRight = new Vector2(bounds.max.x, bounds.min.y);//Bottom Right corner
raycastOrigins.topLeft = new Vector2(bounds.min.x, bounds.max.y); //Top Left corner
raycastOrigins.topRight = new Vector2(bounds.max.x, bounds.max.y);//Top Right corner
}

void CalculateRaySpacing() //Calculates space between rays
{
Bounds bounds = collider.bounds; //set bounds
bounds.Expand(skinWidth * -2); //Shrink

horizontalRayCount = Mathf.Clamp(horizontalRayCount, 2, int.MaxValue); //Need 1 in each corner
verticalRayCount = Mathf.Clamp(verticalRayCount, 2, int.MaxValue); //1 in each corner (vertical)

horizontalRaySpacing = bounds.size.y / (horizontalRayCount - 1); //The size of bounds / n - 1
verticalRaySpacing = bounds.size.x / (verticalRayCount - 1);//The size of bounds / n - 1
}

struct RaycastOrigins //Holds Vector 2's
{
public Vector2 topLeft, topRight;
public Vector2 bottomLeft, bottomRight;
}

public struct CollisionInfo
{
public bool above, below;
public bool left, right;

public void Reset() //Reset the Bools
{
above = below = false;
left = right = false;
}
}

}

11 changes: 11 additions & 0 deletions Platformer/Assets/Scripts/Controller2D.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

146 changes: 47 additions & 99 deletions Platformer/Assets/Scripts/Level 1/Player_Controller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,119 +3,78 @@
using UnityEngine;
using UnityEngine.UI;


[RequireComponent(typeof(Controller2D))]
public class Player_Controller : MonoBehaviour
{
public float speed = 7.5f; //speed
public Rigidbody2D rb; //Rigidbody

public int currentHealth; //health
private int maxHealth = 100; //max health

public HealthBar healthbar; //Healthbar
Controller2D controller; //controller

float moveSpeed = 10; //How Fast He moves

public int cash; //Cash

int jumps; //Amount of jumps available
int maxjumps = 2; //Max amount of Jumps (Double Jump)
float jumpforce = 7.75f; //Force going up (Y axis)
bool grounded = true; //Start Grounded
float gravity; //Gravity (No Rigid Body)
float jumpVelocity;
Vector3 velocity; //Velocity (Again since using raycasting need to create alll this)
float velocityXSmoothing;

private bool FacingRight = true; // Which way is player facing
//Jumping
public float jumpHeight = 4;
public float timeToJumpApex = .4f;
float accelerationTimeAirborne = .2f;
float accelerationTimeGrounded = .1f;

public GameObject door; //Public so I could drag door in, not sure I need to find with tag but leaving as it works

public int currentHealth; //health
private int maxHealth = 100; //max health
public HealthBar healthbar; //Healthbar

public GameObject door; //Public so I could drag door in

void Start()
{
rb = GetComponent<Rigidbody2D>(); //Get rigidbody component from player
door.SetActive(false); // Turn off the door
currentHealth = maxHealth;
healthbar.SetMaxHealth(maxHealth);
}
controller = GetComponent<Controller2D>(); //Get Components controller2d

void Update()
{
//Movement
float moveHorizontal = Input.GetAxis("Horizontal"); // Horizontal Movement
Vector3 movement = new Vector3(moveHorizontal, 0.0f, 0.0f); //No movement in the Y or Z Axies
transform.position += movement * Time.deltaTime * speed; //Transform the position in accordance to movement, times speed, times time passed

if (Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.W)) //Player wants to Jump
{
Jump(); //Go to Jump
}

// moving the player right and the player is facing left...
if (moveHorizontal > 0 && !FacingRight)
{
// flip player.
Flip();
}
// moving the player left and the player is facing right...
else if (moveHorizontal < 0 && FacingRight)
{
// ... flip the player.
Flip();
}
gravity = -(2 * jumpHeight) / Mathf.Pow(timeToJumpApex, 2); //Derived from equation
jumpVelocity = Mathf.Abs(gravity) * timeToJumpApex; //Derived from equation
print("Gravity: " + gravity + " Jump Velocity: " + jumpVelocity);

door.SetActive(false); // Turn off the door
currentHealth = maxHealth; //Reset to max health
healthbar.SetMaxHealth(maxHealth); //Health bar to max
}

void Jump()
void Update()
{
if (jumps > 0) //if there are jumps available
if (controller.collisions.above || controller.collisions.below) //if true reset y
{
rb.AddForce(new Vector2(0, jumpforce), ForceMode2D.Impulse); //then jump
grounded = false; //off the ground
jumps = jumps - 1; //used a jump
velocity.y = 0;
}
if (jumps == 0) //there are no jumps

Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

if (Input.GetKeyDown(KeyCode.Space) && controller.collisions.below) //Jumping (and on something)
{
return; // do nothing
velocity.y = jumpVelocity;
}

float targetVelocityX = input.x * moveSpeed;

velocity.x = Mathf.SmoothDamp(velocity.x, targetVelocityX, ref velocityXSmoothing, (controller.collisions.below) ? accelerationTimeGrounded : accelerationTimeAirborne); //Movement in the x direction
velocity.y += gravity * Time.deltaTime; //Movement in the y Direction
controller.Move(velocity * Time.deltaTime); //How to actually move, in controller script
}


void TakeDamage(int damage) //Take Damage Function

//Damage Function
void TakeDamage(int damage)
{
currentHealth -= damage; //take damage
healthbar.SetHealth(currentHealth); //modify health bar
}



void OnCollisionEnter2D(Collision2D collide) // Collisions
{
if (collide.gameObject.tag == "Box") //if you land on box then you have your jumps back
{
jumps = maxjumps; //2
grounded = true; //on ground
}

if (collide.gameObject.tag == "Bouncer") //if you land on box then you have your jumps back
{
if (FacingRight == true) //Rebound
{
rb.velocity = (new Vector2(-1.5f, 1f));
}

if (FacingRight == false) //Rebound
{
rb.velocity = (new Vector2(1.5f, 1f));
}
}

if (collide.gameObject.CompareTag("Enemy"))
{
TakeDamage(15); //Go to take damage function and pass in the integer 20

if ( currentHealth < 1) //Death
{
Time.timeScale = 0;
}
}


}

//Ontrigger Enter (AKA TAGS)
void OnTriggerEnter2D(Collider2D other) //Pickups
{
if (other.gameObject.CompareTag("Key")) //If you got the key
Expand All @@ -124,27 +83,16 @@ void OnTriggerEnter2D(Collider2D other) //Pickups
door.SetActive(true); // Door is accessible
}

if (other.gameObject.CompareTag("Cash"))
{
other.gameObject.SetActive(false); // cash dissapears
cash = cash + 1; //Add money
}

if (other.gameObject.CompareTag("Heart"))
{
other.gameObject.SetActive(false); // heart dissapears
currentHealth = maxHealth; // Full Health
healthbar.SetHealth(currentHealth); //Full HealthBar
}


//Ninja star is in the weapon script (easier that way for some reason )
}

//Facing Which way
private void Flip()
{
FacingRight = !FacingRight; //if facing right
transform.Rotate(0f, 180f, 0f); //rotate
}


}
Loading

0 comments on commit d8a7b16

Please sign in to comment.