Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///Dan Check 3
- using UnityEngine;
- using System.Collections;
- using UnityStandardAssets.CrossPlatformInput; //joystick controls
- [RequireComponent(typeof(MovementMotor))]
- [RequireComponent(typeof(AudioSource))]
- public class PlayerMovement : MonoBehaviour
- {
- //General Setup
- public Transform mainCamera;
- public Animator animator;
- private MovementMotor movementMotor; //Movement MotorScript
- private PlayerHealth playerHealth;
- public float fallDistanceBeforeRespawn = -100f;
- public GameObject[] enemiesArray;
- public Vector3 directionToRun;
- private Transform target; //Stores the target the bomb lock onto
- private bool targetSelected; //has a target been found
- public float HommingRadious = 20f;
- //public SphereCollider HommingRadious;
- public bool AmICharging = false;
- Vector3 dir;
- public float thrust = 20f;
- public float speed = 4f;
- //Movement Input Variable
- private bool jump;
- public static float h;
- public static float v;
- //Movement Settings
- private float currentAcceleration, currentDeceleration, currentRotateSpeed;
- public float acceleration = 70f, airAcceleration = 18f; //acceleration/deceleration in air or on the ground
- public float deceleration = 7.6f, airDeceleration = 1.1f;
- [Range(0f, 5f)]
- public float rotateSpeed = 0.7f, airRotateSpeed = 0.4f; //how fast to rotate on the ground, how fast to rotate in the air
- public float maxSpeed = 9; //maximum speed of movement in X/Z axis
- public float trainFriction = 7.7f; //you'll need to tweak this to get the player to stay on moving platforms properly
- public float lift = 20;
- //Rotate on spot variables
- public static bool rotateOnSpot = false;
- //public static bool doNotMoveIfStationary = false; ?????? Dont think we need this
- public float rotateOnSpotSpeed = 4f;
- public float stoppingToRotateOnSpotSpeed = 10.0f;
- //Ground Check variables
- public static bool grounded; // public static bool grounded;
- private float groundedCount;
- //Jump Settings
- public static bool jumpAllowed = true; //Allows Jump to be deactivated if you so not whish the p;ayer to jump
- public float timeBetweenJumps = 0.15f; //Allows a time between jumps to be set
- public Vector3 jumpForce = new Vector3(0, 13, 0); //jump force
- Vector3 oldVel;
- //Direction variables
- private Quaternion cameraRotation;
- private Vector3 direction, moveDirection, movementForwardMultipliedByCameraRotation, movementRightMultipliedByCameraRotation, trainSpeed;
- //Sound FX
- public AudioClip jumpSound; //plays when jumping
- public AudioClip landJumpSound; //plays when landing on ground
- public bool landedJumpSound;
- private Rigidbody playerRigidbody;//public 2019 was private
- //Components
- private AudioSource playerAudioSource;
- //setup
- void Awake()
- {
- //assign "Player" tag if not assigned
- if (tag != "Player")
- {
- tag = "Player";
- Debug.LogWarning("This gameobject was automaticly tagged as player by the PlayerMovement Script", transform);
- }
- //Assigns main camera is not assigned
- if (!mainCamera)
- {
- mainCamera = GameObject.FindGameObjectWithTag("MainCamera").transform;
- }
- //Get scripts
- movementMotor = GetComponent<MovementMotor>();
- playerHealth = GetComponent<PlayerHealth>();
- playerAudioSource = GetComponent<AudioSource>();
- playerRigidbody = GetComponent<Rigidbody>();
- // enemiesArray = GameObject.FindGameObjectsWithTag("Enemy");
- }
- void Update()
- {
- //inputs
- #if CROSS_PLATFORM_INPUT
- jump = CrossPlatformInputManager.GetButton("Jump"); //Get Button Mobile Jump
- h = CrossPlatformInputManager.GetAxis("Horizontal"); //Get Axis Mobile Horizontal
- v = CrossPlatformInputManager.GetAxis("Vertical"); //Get Axis Mobile Vertical
- #else
- jump = Input.GetButton("Jump"); //Get Jump
- h = Input.GetAxis("Horizontal"); //Get Axis Horizontal
- v = Input.GetAxis("Vertical"); //Get Axis Vertical
- #endif
- //get movement axis relative to camera
- //Stops the player from turning too sharp
- cameraRotation = Quaternion.Euler(0, mainCamera.eulerAngles.y, 0);
- movementForwardMultipliedByCameraRotation = cameraRotation * Vector3.forward;
- movementRightMultipliedByCameraRotation = cameraRotation * Vector3.right;
- //Adds horizontal and vertical input to get direction this is then passed to the movement motor
- direction = (movementForwardMultipliedByCameraRotation * v) + (movementRightMultipliedByCameraRotation * h);
- moveDirection = transform.position + direction;
- if (Input.GetKeyDown(KeyCode.Space))//y
- {
- if (grounded == false)//
- {
- TargetEnemy();
- // if (TargetEnemy !=null)// null reference check
- // {
- // ;
- //}
- moveDirection = transform.position + (target.position - transform.position);
- Invoke("noSelction", 3f);
- //
- // playerRigidbody.AddForce(transform.forward * thrust);
- //grounded = true;
- }
- }
- }
- /* function blu OnTriggerEnter(other:Collider)
- {
- if (other.gameobject.tag == "whateveryoucallthecollider")
- {
- enemyObject = other.gameobject;
- enemyarray++; // This will increment the counter
- // do whatever else you want here
- //debug.log("Enemy added to array.");
- }
- */
- /* private void OnTriggerEnter(Collider other)
- {
- //enemiesArray gameObject.tag == "ground";
- //GameObject.FindGameObjectsWithTag("Enemy");
- if (other.gameObject.tag == "Enemy")
- {
- enemiesArray = GameObject.FindGameObjectsWithTag("Enemy");
- // private void OnTriggerExit(Collider other)//solution i think
- //{
- if (other.gameObject.CompareTag("Enemy"))
- {
- enemiesArray = null;
- }
- //}
- //enemiesArray =
- //enemiesArray = other.gameobject;
- // enemiesArray ++; // This will increment the counter
- // do whatever else you want here
- //debug.log("Enemy added to array.");
- }
- }
- private void OnTriggerExit(Collider other)//solution i think
- {
- // enemiesArray = GameObject.FindGameObjectsWithTag("Enemy");
- enemiesArray = null;
- }
- */
- private void OnTriggerEnter(Collider other)
- {
- if (other.gameObject.tag == "Enemy")
- {
- enemiesArray = GameObject.FindGameObjectsWithTag("Enemy");
- }
- }
- private void OnTriggerExit(Collider other)//solution i think
- {
- if (other.gameObject.CompareTag("Enemy"))
- {
- enemiesArray = null;
- }
- }
- void noSelction()
- {
- targetSelected = false;
- }
- void TargetEnemy()
- {
- //If there are enemies in the list it loops though and finds the closest enemy to the player
- if (enemiesArray.Length != 0)
- {
- GameObject l = enemiesArray[0]; //Selects the first enemey
- //Loops through enemy list and find the closest enemy to the player
- foreach (GameObject enemy in enemiesArray)
- {
- GameObject r = enemy;
- if (Vector3.Distance(transform.position, r.transform.position) < Vector3.Distance(transform.position, l.transform.position))
- {
- l = r;
- // Debug.Log("found " + l.name);
- }
- }
- //When the closest target is found it stores it is stored in target and targetSelected is set to true
- target = l.transform;
- targetSelected = true;
- FaceEnemy(target.gameObject);
- }
- else
- {
- targetSelected = false;
- }
- }
- void FaceEnemy(GameObject ob)
- {
- transform.LookAt(ob.transform.position);
- float measurment = Vector3.Distance(ob.transform.position, transform.position);
- dir = ob.transform.position - transform.position;
- if (measurment <= HommingRadious)
- // public void OnTriggerEnter(Collider HommingRadious)
- {
- AmICharging = true;
- Invoke("NotCharging", 3f);//play around here
- // playerRigidbody.velocity = new Vector3(0, 10, 0);// ithink this should work//direction times speed
- playerRigidbody.velocity = dir * speed;//this should work
- }
- else
- {
- // AmICharging = true;
- //Invoke("NotCharging", 3f);//
- dir = transform.forward;
- }
- /*void FaceEnemy(GameObject ob)
- {
- transform.LookAt(ob.transform.position);
- float measurment = Vector3.Distance(ob.transform.position, transform.position);
- dir = ob.transform.position - transform.position;
- if (measurment <= HommingRadious)
- {
- AmICharging = true;
- Invoke("NotCharging", 3f);//play around here
- }
- else
- {
- AmICharging = true;
- Invoke("NotCharging", 3f);
- dir = transform.forward;
- }
- */
- }
- void NotCharging()
- {
- AmICharging = false;
- }
- //apply correct player movement (fixedUpdate for physics calculations)
- void FixedUpdate()
- {
- //Returns true if we are grounded
- grounded = IsGrounded();
- //adjust the movement values depending if we are on the gound or in the air
- if (targetSelected)
- {
- currentAcceleration = 1000;
- currentDeceleration = deceleration;
- currentRotateSpeed = rotateSpeed;
- }
- else if (grounded)
- {
- currentAcceleration = acceleration;
- currentDeceleration = deceleration;
- currentRotateSpeed = rotateSpeed;
- }
- else
- {
- currentAcceleration = airAcceleration;
- currentDeceleration = airDeceleration;
- currentRotateSpeed = airRotateSpeed;
- }
- MovePlayer(); //Player move controls function
- Jumping(); //Player Jump control function
- if (AmICharging == true)
- {
- playerRigidbody.AddForce(dir * thrust);
- }
- }
- // moves the player
- void MovePlayer()
- {
- //Stop the player from moving and calls a function in the MovsementMotor to rotate the character on the spot
- if (animator && rotateOnSpot)
- {
- animator.SetFloat("TurnLeftOrRight", h);
- animator.SetBool("Grounded", grounded);
- animator.SetFloat("DistanceToTarget", 0);
- movementMotor.RotateOnSpot(h, rotateOnSpotSpeed, stoppingToRotateOnSpotSpeed);
- return;
- }
- //move, rotate,
- movementMotor.MoveToDestination(moveDirection, currentAcceleration, 0.7f);
- if (rotateSpeed != 0 && direction.magnitude != 0)
- {
- movementMotor.RotateToDirection(moveDirection, currentRotateSpeed * 5);
- }
- //manage speed
- movementMotor.ManageSpeed(currentDeceleration, maxSpeed + trainSpeed.magnitude);
- //set animation values
- if (animator)
- {
- animator.SetFloat("TurnLeftOrRight", 0);
- animator.SetFloat("DistanceToTarget", movementMotor.distanceToTarget);
- animator.SetBool("Grounded", grounded);
- animator.SetFloat("YVelocity", playerRigidbody.velocity.y);
- }
- //Fall off the edge check
- if (transform.position.y < fallDistanceBeforeRespawn)
- {
- //Calls the Death function in player helath if you fall off the edge
- playerHealth.Death();
- }
- }
- //returns true if the player is on the ground returns false if the player is in the air
- private bool IsGrounded()
- {
- //get distance to ground, from centre of collider
- float distanceToGround = GetComponent<Collider>().bounds.extents.y;
- //This raycast is used to check to see what is below the player and if it has a collider on it
- RaycastHit hit;
- if (Physics.Raycast(transform.position, Vector3.down, out hit, distanceToGround + 0.1f))
- {
- //if we the raycast hits a collider that is not a trigger
- if (hit.transform.GetComponent<Collider>().isTrigger == false)
- {
- //moving platforms
- if (hit.transform.tag == "Train")
- {
- trainSpeed = hit.transform.GetComponent<Rigidbody>().velocity;
- //9.5f is a magic number, if youre not moving properly on platforms, experiment with this number
- playerRigidbody.AddForce(trainSpeed * trainFriction * Time.fixedDeltaTime, ForceMode.VelocityChange);
- }
- else
- {
- trainSpeed = Vector3.zero;
- }
- //tracks the time you are on the ground
- groundedCount += Time.deltaTime; //Counts the time you are on the ground
- return true; //Returns true if the player is on a collider that is not a trigger
- }
- }
- trainSpeed = Vector3.zero;
- groundedCount = 0f; //Resets groundCount time
- return false; //Returns false if the player is in the air or on a collider that is a trigger
- }
- //Checks if the player should be able to jump
- private void Jumping()
- {
- //Stops the player from jumping if this jumpAllowed is = to false
- //This can be used to disable the players ability to Jump
- if (!jumpAllowed)
- {
- return;
- }
- //play landing sound
- if (groundedCount < 1 && groundedCount != 0 && !playerAudioSource.isPlaying && landJumpSound && playerRigidbody.velocity.y < 1 && !landedJumpSound)
- {
- playerAudioSource.clip = landJumpSound;
- playerAudioSource.volume = 0.1f;
- playerAudioSource.Play();
- landedJumpSound = true;
- }
- if (grounded && groundedCount > timeBetweenJumps && !rotateOnSpot)
- {
- if (jump)
- {
- Jump(jumpForce);
- }
- }
- }
- void OnCollisionEnter(Collision collision)
- {
- ContactPoint contact = collision.contacts[0];
- //if ((Input.GetKeyDown(KeyCode.Space) && collision.gameObject.tag == "Wall"))
- if (collision.gameObject.tag == "Wall")
- {
- //if ((Input.GetKeyDown(KeyCode.Space)))
- // {
- // calculate with addition of normal vector
- //playerRigidbody.velocity = oldVel + cp.normal*2.0f*oldVel.magnitude;
- // calculate with Vector3.Reflect
- playerRigidbody.velocity = Vector3.Reflect(oldVel, contact.normal);
- // bumper effect to speed up ball
- playerRigidbody.velocity += contact.normal * 120f;
- playerRigidbody.velocity = new Vector3(playerRigidbody.velocity.x, 0f, playerRigidbody.velocity.z);
- playerRigidbody.AddForce(Vector3.up * lift, ForceMode.Impulse);
- }
- }
- //Adds Jump Force
- public void Jump(Vector3 jumpVelocity)
- {
- //play jump sound
- if (jumpSound && !playerAudioSource.isPlaying)
- {
- playerAudioSource.clip = jumpSound;
- playerAudioSource.volume = 0.1f;
- playerAudioSource.Play();
- landedJumpSound = false;
- }
- //Adds Jump Force
- playerRigidbody.velocity = new Vector3(playerRigidbody.velocity.x, 0f, playerRigidbody.velocity.z);
- playerRigidbody.AddRelativeForce(jumpVelocity, ForceMode.Impulse);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement