Advertisement
Guest User

Untitled

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