Newer
Older
HardPoint-Project-Abertay-University-Unity3D / Assets / Scripts / Entities / Movement.cs
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Scripting.APIUpdating;

public class Movement : MonoBehaviour, IMovable
{
    private Rigidbody rb;
    private bool colliding = false;
    private bool statusChanged = false;
    private bool blockMovement = false;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }    
    bool IMovable.OnGround()
    {
        //Checks if the vertical velocity is different then 0 to know if he is falling. If it is different then 0 means that it is on air.
        if (Mathf.Abs(rb.velocity.y) < 0.5)
        {
            if (colliding)
            {
                if (statusChanged)
                {
                    RaycastHit hit;
                    if (Physics.Raycast(transform.position, Vector3.down, out hit))
                    {
                        //Makes sure that the player is on ground.
                        if (hit.distance < transform.localScale.y / 2 + 0.2)
                        {
                            //Debug.Log("Raycasting");
                            statusChanged = false;
                            return true;
                        }
                    }
                }
                else return true;
            }
        }
        return false;
    }
    void IMovable.ChangeDrag(float drag)
    {
        rb.drag = drag;
    }
    void IMovable.ChangeVelocity(Vector3 velocity)
    {
        rb.velocity = velocity;
    }

    void IMovable.ToggleGravity(bool b)
    {
        rb.useGravity= b;
    }
    bool IMovable.GetGravity()
    {
        return rb.useGravity;
    }
    Vector3 IMovable.GetVelocity()
    {
        return rb.velocity;
    }
    void IMovable.AddForce(Vector3 force)
    {
        rb.AddForce(force);
    }
    void IMovable.Move(Vector3 direction, float speed, float acceleration)
    {
        //Just changes the current velocity to the new one without changing the Y values.
        rb.velocity = new Vector3(direction.x * acceleration, rb.velocity.y, direction.z * acceleration);
        //Debug.Log(rb.velocity);
        //Debug.Log("Gravity: " + Physics.gravity);
    }
    bool IMovable.IsColliding() { return colliding; }
    void IMovable.SetBlockMovement(bool b)
    {
        blockMovement = b;
    }
    bool IMovable.GetBlockMovement()
    {
        return blockMovement;
    }

    private void OnCollisionStay(Collision collision)
    {
        if (!colliding) statusChanged = true;
        colliding = true;
    }
    private void OnCollisionExit(Collision collision)
    {
        //Debug.Log("Exiting collision");
        if (colliding) statusChanged = true;
        colliding = false;
    }
}