Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class CharacterGravity : MonoBehaviour
- {
- private Rigidbody rb;
- public bool gravityOn;
- private float avoidGravity = 9.81f * 2.0f * 1.0f; //To transform gravity to its inverse.
- private float normalGravity = 0.0f; //To get the normal gravity.
- private Vector3 floor; //It'll set the distance until the point just under you.
- private Vector3 roof; //It'll set the distance until the point just above you.
- public GameObject onRoof; //Empty GameObject with the xyz reference which will have the player on roof.
- public GameObject onFloor; //Empty GameObject with the xyz reference which will have the player on floor.
- public GameObject turnReference; //It takes values from onRoof and onFloor depending on the gravity values.
- private float distanceTo; //It calculates everytime the distance to the surface which is not being walked by the player.
- private float distanceToValor; //It sets the value from distanceTo when the change of gravity is activated.
- private float gradesPerSecond; //It calculates the grades that the player has to rotate per second to land standing on the surface.
- // Use this for initialization
- void Start()
- {
- rb = GetComponent<Rigidbody>();
- gravityOn = true;
- referenciaGiro = onFloor;
- }
- // Update is called once per frame
- void Update()
- {
- }
- private void FixedUpdate()
- {
- Gravity();
- LerpRoof();
- }
- void Gravity() //Change values of the gravity force which affetcs the player.
- {
- if (Input.GetKeyDown(KeyCode.C))
- {
- gravityOn = !gravityOn;
- distanceToValor = distanceTo;
- }
- if (gravityOn)
- {
- rb.AddForce(new Vector3(0, normalGravity, 0));
- }
- else
- {
- rb.AddForce(new Vector3(0, avoidGravity, 0));
- }
- }
- void LerpRoof()
- {
- if (gravityOn)
- {
- RaycastHit hit;
- // Roof detection.
- Ray upRay = new Ray (transform.position, Vector3.up);
- if (Physics.Raycast( upRay, out hit))
- {
- Debug.Log("Collider es " + hit.collider.name);
- roof = hit.point;
- distanceTo = Vector3.Distance(transform.position, hit.point);
- }
- else
- {
- }
- }
- else
- {
- RaycastHit hit;
- // Floor detection.
- Ray downRay = new Ray(transform.position, Vector3.down);
- if (Physics.Raycast(downRay, out hit))
- {
- floor = hit.point;
- distanceTo = Vector3.Distance(transform.position, floor);
- }
- else
- {
- }
- }
- //Change of rotation reference to roof/floor.
- gradesPerSecond = (180/ (((2.0f * distanceToValor) / 3.0f) / Physics.gravity.magnitude));
- if (Input.GetKeyDown(KeyCode.C) && gravityOn == true)
- {
- turnReference = onFloor;
- }
- if (Input.GetKeyDown(KeyCode.C) && gravityOn == false)
- {
- turnReference = onRoof;
- }
- transform.rotation = Quaternion.RotateTowards(transform.rotation, turnReference.transform.rotation, gradesPerSecond * Time.deltaTime);
- }
- }
Add Comment
Please, Sign In to add comment