Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.98 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityStandardAssets.CrossPlatformInput; //joystick controls
  4.  
  5. [RequireComponent(typeof(MovementMotor))]
  6. [RequireComponent(typeof(AudioSource))]
  7.  
  8. public class PlayerMovement : MonoBehaviour
  9. {
  10. //General Setup
  11. public Transform mainCamera;
  12. public Animator animator;
  13. private MovementMotor movementMotor; //Movement MotorScript
  14. private PlayerHealth playerHealth;
  15. public float fallDistanceBeforeRespawn = -100f;
  16.  
  17. public GameObject[] enemiesArray;
  18.  
  19. public Vector3 directionToRun;
  20. private Transform target; //Stores the target the bomb lock onto
  21. private bool targetSelected; //has a target been found
  22. public float HommingRadious = 20f;
  23. //public SphereCollider HommingRadious;
  24. public bool AmICharging = false;
  25. Vector3 dir;
  26. public float thrust = 20f;
  27.  
  28. public float speed = 4f;
  29.  
  30. //Movement Input Variable
  31. private bool jump;
  32. public static float h;
  33. public static float v;
  34.  
  35. //Movement Settings
  36. private float currentAcceleration, currentDeceleration, currentRotateSpeed;
  37. public float acceleration = 70f, airAcceleration = 18f; //acceleration/deceleration in air or on the ground
  38. public float deceleration = 7.6f, airDeceleration = 1.1f;
  39. [Range(0f, 5f)]
  40. public float rotateSpeed = 0.7f, airRotateSpeed = 0.4f; //how fast to rotate on the ground, how fast to rotate in the air
  41. public float maxSpeed = 9; //maximum speed of movement in X/Z axis
  42. public float trainFriction = 7.7f; //you'll need to tweak this to get the player to stay on moving platforms properly
  43. public float lift = 20;
  44.  
  45. //Rotate on spot variables
  46. public static bool rotateOnSpot = false;
  47. //public static bool doNotMoveIfStationary = false; ?????? Dont think we need this
  48. public float rotateOnSpotSpeed = 4f;
  49. public float stoppingToRotateOnSpotSpeed = 10.0f;
  50.  
  51. //Ground Check variables
  52. public static bool grounded; // public static bool grounded;
  53. private float groundedCount;
  54.  
  55. //Jump Settings
  56. public static bool jumpAllowed = true; //Allows Jump to be deactivated if you so not whish the p;ayer to jump
  57. public float timeBetweenJumps = 0.15f; //Allows a time between jumps to be set
  58. public Vector3 jumpForce = new Vector3(0, 13, 0); //jump force
  59. Vector3 oldVel;
  60.  
  61. //Direction variables
  62. private Quaternion cameraRotation;
  63. private Vector3 direction, moveDirection, movementForwardMultipliedByCameraRotation, movementRightMultipliedByCameraRotation, trainSpeed;
  64.  
  65. //Sound FX
  66. public AudioClip jumpSound; //plays when jumping
  67. public AudioClip landJumpSound; //plays when landing on ground
  68. public bool landedJumpSound;
  69. private Rigidbody playerRigidbody;//public 2019 was private
  70. //Components
  71. private AudioSource playerAudioSource;
  72.  
  73. //setup
  74. void Awake()
  75. {
  76. //assign "Player" tag if not assigned
  77. if (tag != "Player")
  78. {
  79. tag = "Player";
  80. Debug.LogWarning("This gameobject was automaticly tagged as player by the PlayerMovement Script", transform);
  81. }
  82. //Assigns main camera is not assigned
  83. if (!mainCamera)
  84. {
  85. mainCamera = GameObject.FindGameObjectWithTag("MainCamera").transform;
  86. }
  87. //Get scripts
  88. movementMotor = GetComponent<MovementMotor>();
  89. playerHealth = GetComponent<PlayerHealth>();
  90. playerAudioSource = GetComponent<AudioSource>();
  91. playerRigidbody = GetComponent<Rigidbody>();
  92. // enemiesArray = GameObject.FindGameObjectsWithTag("Enemy");
  93. }
  94.  
  95.  
  96. void Update()
  97. {
  98. //inputs
  99. #if CROSS_PLATFORM_INPUT
  100. jump = CrossPlatformInputManager.GetButton("Jump"); //Get Button Mobile Jump
  101. h = CrossPlatformInputManager.GetAxis("Horizontal"); //Get Axis Mobile Horizontal
  102. v = CrossPlatformInputManager.GetAxis("Vertical"); //Get Axis Mobile Vertical
  103. #else
  104. jump = Input.GetButton("Jump"); //Get Jump
  105. h = Input.GetAxis("Horizontal"); //Get Axis Horizontal
  106. v = Input.GetAxis("Vertical"); //Get Axis Vertical
  107. #endif
  108.  
  109. //get movement axis relative to camera
  110. //Stops the player from turning too sharp
  111. cameraRotation = Quaternion.Euler(0, mainCamera.eulerAngles.y, 0);
  112. movementForwardMultipliedByCameraRotation = cameraRotation * Vector3.forward;
  113. movementRightMultipliedByCameraRotation = cameraRotation * Vector3.right;
  114.  
  115.  
  116. //Adds horizontal and vertical input to get direction this is then passed to the movement motor
  117. direction = (movementForwardMultipliedByCameraRotation * v) + (movementRightMultipliedByCameraRotation * h);
  118. moveDirection = transform.position + direction;
  119.  
  120. if (Input.GetKeyDown(KeyCode.Space))//y
  121. {
  122. if (grounded == false)//
  123. {
  124. TargetEnemy();
  125. moveDirection = transform.position + (target.position - transform.position);
  126. Invoke("noSelction", 3f);
  127. //
  128. // playerRigidbody.AddForce(transform.forward * thrust);
  129. //grounded = true;
  130. }
  131.  
  132. }
  133.  
  134.  
  135.  
  136.  
  137. }
  138. private void OnTriggerEnter(Collider other)
  139. {
  140. enemiesArray gameObject.tag == "ground";
  141. //GameObject.FindGameObjectsWithTag("Enemy");
  142. }
  143. private void OnTriggerExit(Collider other)//solution i think
  144. {
  145. // enemiesArray = GameObject.FindGameObjectsWithTag("Enemy");
  146. enemiesArray = null;
  147. }
  148.  
  149.  
  150. void noSelction()
  151. {
  152. targetSelected = false;
  153. }
  154.  
  155.  
  156. void TargetEnemy()
  157. {
  158. //If there are enemies in the list it loops though and finds the closest enemy to the player
  159. if (enemiesArray.Length != 0)
  160. {
  161. GameObject l = enemiesArray[0]; //Selects the first enemey
  162. //Loops through enemy list and find the closest enemy to the player
  163. foreach (GameObject enemy in enemiesArray)
  164. {
  165. GameObject r = enemy;
  166. if (Vector3.Distance(transform.position, r.transform.position) < Vector3.Distance(transform.position, l.transform.position))
  167. {
  168. l = r;
  169. // Debug.Log("found " + l.name);
  170. }
  171. }
  172. //When the closest target is found it stores it is stored in target and targetSelected is set to true
  173. target = l.transform;
  174. targetSelected = true;
  175. FaceEnemy(target.gameObject);
  176. }
  177. else
  178. {
  179. targetSelected = false;
  180. }
  181. }
  182. void FaceEnemy(GameObject ob)
  183. {
  184. transform.LookAt(ob.transform.position);
  185. float measurment = Vector3.Distance(ob.transform.position, transform.position);
  186. dir = ob.transform.position - transform.position;
  187. if (measurment <= HommingRadious)
  188. // public void OnTriggerEnter(Collider HommingRadious)
  189. {
  190. AmICharging = true;
  191. Invoke("NotCharging", 3f);//play around here
  192. // playerRigidbody.velocity = new Vector3(0, 10, 0);// ithink this should work//direction times speed
  193. playerRigidbody.velocity = dir * speed;//this should work
  194. }
  195. else
  196. {
  197. // AmICharging = true;
  198. //Invoke("NotCharging", 3f);//
  199. dir = transform.forward;
  200. }
  201.  
  202.  
  203. /*void FaceEnemy(GameObject ob)
  204. {
  205. transform.LookAt(ob.transform.position);
  206. float measurment = Vector3.Distance(ob.transform.position, transform.position);
  207. dir = ob.transform.position - transform.position;
  208.  
  209. if (measurment <= HommingRadious)
  210. {
  211. AmICharging = true;
  212. Invoke("NotCharging", 3f);//play around here
  213. }
  214. else
  215. {
  216. AmICharging = true;
  217. Invoke("NotCharging", 3f);
  218. dir = transform.forward;
  219. }
  220. */
  221.  
  222.  
  223. }
  224. void NotCharging()
  225. {
  226. AmICharging = false;
  227. }
  228.  
  229.  
  230. //apply correct player movement (fixedUpdate for physics calculations)
  231. void FixedUpdate()
  232. {
  233. //Returns true if we are grounded
  234. grounded = IsGrounded();
  235.  
  236.  
  237. //adjust the movement values depending if we are on the gound or in the air
  238.  
  239. if (targetSelected)
  240. {
  241. currentAcceleration = 1000;
  242. currentDeceleration = deceleration;
  243. currentRotateSpeed = rotateSpeed;
  244. }
  245. else if (grounded)
  246. {
  247. currentAcceleration = acceleration;
  248. currentDeceleration = deceleration;
  249. currentRotateSpeed = rotateSpeed;
  250. }
  251. else
  252. {
  253. currentAcceleration = airAcceleration;
  254. currentDeceleration = airDeceleration;
  255. currentRotateSpeed = airRotateSpeed;
  256. }
  257.  
  258.  
  259. MovePlayer(); //Player move controls function
  260. Jumping(); //Player Jump control function
  261. if (AmICharging == true)
  262. {
  263. playerRigidbody.AddForce(dir * thrust);
  264. }
  265. }
  266.  
  267.  
  268. // moves the player
  269. void MovePlayer()
  270. {
  271.  
  272.  
  273.  
  274. //Stop the player from moving and calls a function in the MovsementMotor to rotate the character on the spot
  275. if (animator && rotateOnSpot)
  276. {
  277. animator.SetFloat("TurnLeftOrRight", h);
  278. animator.SetBool("Grounded", grounded);
  279. animator.SetFloat("DistanceToTarget", 0);
  280. movementMotor.RotateOnSpot(h, rotateOnSpotSpeed, stoppingToRotateOnSpotSpeed);
  281. return;
  282. }
  283.  
  284. //move, rotate,
  285. movementMotor.MoveToDestination(moveDirection, currentAcceleration, 0.7f);
  286.  
  287. if (rotateSpeed != 0 && direction.magnitude != 0)
  288. {
  289. movementMotor.RotateToDirection(moveDirection, currentRotateSpeed * 5);
  290. }
  291. //manage speed
  292. movementMotor.ManageSpeed(currentDeceleration, maxSpeed + trainSpeed.magnitude);
  293.  
  294. //set animation values
  295. if (animator)
  296. {
  297. animator.SetFloat("TurnLeftOrRight", 0);
  298. animator.SetFloat("DistanceToTarget", movementMotor.distanceToTarget);
  299. animator.SetBool("Grounded", grounded);
  300. animator.SetFloat("YVelocity", playerRigidbody.velocity.y);
  301. }
  302. //Fall off the edge check
  303. if (transform.position.y < fallDistanceBeforeRespawn)
  304. {
  305. //Calls the Death function in player helath if you fall off the edge
  306. playerHealth.Death();
  307.  
  308. }
  309. }
  310.  
  311. //returns true if the player is on the ground returns false if the player is in the air
  312. private bool IsGrounded()
  313. {
  314. //get distance to ground, from centre of collider
  315. float distanceToGround = GetComponent<Collider>().bounds.extents.y;
  316. //This raycast is used to check to see what is below the player and if it has a collider on it
  317. RaycastHit hit;
  318. if (Physics.Raycast(transform.position, Vector3.down, out hit, distanceToGround + 0.1f))
  319. {
  320. //if we the raycast hits a collider that is not a trigger
  321. if (hit.transform.GetComponent<Collider>().isTrigger == false)
  322. {
  323. //moving platforms
  324. if (hit.transform.tag == "Train")
  325. {
  326. trainSpeed = hit.transform.GetComponent<Rigidbody>().velocity;
  327. //9.5f is a magic number, if youre not moving properly on platforms, experiment with this number
  328. playerRigidbody.AddForce(trainSpeed * trainFriction * Time.fixedDeltaTime, ForceMode.VelocityChange);
  329. }
  330. else
  331. {
  332. trainSpeed = Vector3.zero;
  333. }
  334. //tracks the time you are on the ground
  335. groundedCount += Time.deltaTime; //Counts the time you are on the ground
  336. return true; //Returns true if the player is on a collider that is not a trigger
  337. }
  338. }
  339. trainSpeed = Vector3.zero;
  340. groundedCount = 0f; //Resets groundCount time
  341. return false; //Returns false if the player is in the air or on a collider that is a trigger
  342. }
  343.  
  344. //Checks if the player should be able to jump
  345. private void Jumping()
  346. {
  347. //Stops the player from jumping if this jumpAllowed is = to false
  348. //This can be used to disable the players ability to Jump
  349. if (!jumpAllowed)
  350. {
  351. return;
  352. }
  353.  
  354. //play landing sound
  355. if (groundedCount < 1 && groundedCount != 0 && !playerAudioSource.isPlaying && landJumpSound && playerRigidbody.velocity.y < 1 && !landedJumpSound)
  356. {
  357. playerAudioSource.clip = landJumpSound;
  358. playerAudioSource.volume = 0.1f;
  359. playerAudioSource.Play();
  360. landedJumpSound = true;
  361. }
  362.  
  363. if (grounded && groundedCount > timeBetweenJumps && !rotateOnSpot)
  364. {
  365. if (jump)
  366. {
  367. Jump(jumpForce);
  368. }
  369. }
  370. }
  371.  
  372. void OnCollisionEnter(Collision collision)
  373. {
  374. ContactPoint contact = collision.contacts[0];
  375. //if ((Input.GetKeyDown(KeyCode.Space) && collision.gameObject.tag == "Wall"))
  376. if (collision.gameObject.tag == "Wall")
  377. {
  378. //if ((Input.GetKeyDown(KeyCode.Space)))
  379. // {
  380.  
  381.  
  382. // calculate with addition of normal vector
  383. //playerRigidbody.velocity = oldVel + cp.normal*2.0f*oldVel.magnitude;
  384.  
  385. // calculate with Vector3.Reflect
  386. playerRigidbody.velocity = Vector3.Reflect(oldVel, contact.normal);
  387.  
  388. // bumper effect to speed up ball
  389. playerRigidbody.velocity += contact.normal * 120f;
  390. playerRigidbody.velocity = new Vector3(playerRigidbody.velocity.x, 0f, playerRigidbody.velocity.z);
  391. playerRigidbody.AddForce(Vector3.up * lift, ForceMode.Impulse);
  392.  
  393. }
  394. }
  395. //Adds Jump Force
  396. public void Jump(Vector3 jumpVelocity)
  397. {
  398. //play jump sound
  399. if (jumpSound && !playerAudioSource.isPlaying)
  400. {
  401. playerAudioSource.clip = jumpSound;
  402. playerAudioSource.volume = 0.1f;
  403. playerAudioSource.Play();
  404. landedJumpSound = false;
  405. }
  406. //Adds Jump Force
  407. playerRigidbody.velocity = new Vector3(playerRigidbody.velocity.x, 0f, playerRigidbody.velocity.z);
  408. playerRigidbody.AddRelativeForce(jumpVelocity, ForceMode.Impulse);
  409. }
  410.  
  411.  
  412.  
  413. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement