Advertisement
Guest User

Untitled

a guest
Oct 21st, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.00 KB | None | 0 0
  1. # Super Mario 64 HD Remake
  2.  
  3. using UnityEngine;
  4. using System;
  5. using System.Linq;
  6. using System.Collections.Generic;
  7.  
  8. /// <summary>
  9. /// Custom character controller, to be used by attaching the component to an object
  10. /// and writing scripts attached to the same object that recieve the "SuperUpdate" message
  11. /// </summary>
  12. public class SuperCharacterController : MonoBehaviour
  13. {
  14. [SerializeField]
  15. public Vector3 debugMove = Vector3.zero;
  16.  
  17. [SerializeField]
  18. bool fixedTimeStep;
  19.  
  20. [SerializeField]
  21. int fixedUpdatesPerSecond;
  22.  
  23. [SerializeField]
  24. bool debugSpheres;
  25.  
  26. [SerializeField]
  27. bool debugPushbackMesssages;
  28.  
  29. /// <summary>
  30. /// Describes the Transform of the object we are standing on as well as it's CollisionType, as well
  31. /// as how far the ground is below us and what angle it is in relation to the controller.
  32. /// </summary>
  33. [SerializeField]
  34. public struct Ground
  35. {
  36. public RaycastHit Hit;
  37. public RaycastHit NearHit;
  38. public RaycastHit FarHit;
  39. public SuperCollisionType CollisionType;
  40. public Transform Transform;
  41.  
  42. public Ground(RaycastHit hit, RaycastHit nearHit, RaycastHit farHit, SuperCollisionType superCollisionType, Transform hitTransform)
  43. {
  44. Hit = hit;
  45. NearHit = nearHit;
  46. FarHit = farHit;
  47. CollisionType = superCollisionType;
  48. Transform = hitTransform;
  49. }
  50. }
  51.  
  52. [SerializeField]
  53. CollisionSphere[] spheres =
  54. new CollisionSphere[3] {
  55. new CollisionSphere(0.5f, true, false),
  56. new CollisionSphere(1.0f, false, false),
  57. new CollisionSphere(1.5f, false, true),
  58. };
  59.  
  60. public LayerMask Walkable;
  61.  
  62. [SerializeField]
  63. Collider OwnCollider;
  64.  
  65. public float radius = 0.5f;
  66.  
  67. public float deltaTime { get; private set; }
  68. public Ground currentGround { get; private set; }
  69. public CollisionSphere feet { get; private set; }
  70. public CollisionSphere head { get; private set; }
  71. public float height { get { return Vector3.Distance(OffsetPosition(head.Offset), OffsetPosition(feet.Offset)); } }
  72. public Vector3 up { get { return transform.up; } }
  73. public Vector3 down { get { return -transform.up; } }
  74. public List<SuperCollision> collisionData { get; private set; }
  75. public Transform currentlyClampedTo { get; set; }
  76.  
  77. private Vector3 initialPosition;
  78. private Vector3 groundOffset;
  79. private bool clamping = true;
  80. private bool slopeLimiting = true;
  81.  
  82. private List<Collider> ignoredColliders;
  83. private List<IgnoredCollider> ignoredColliderStack;
  84.  
  85. private const float Tolerance = 0.05f;
  86. private const float TinyTolerance = 0.01f;
  87. private const string TemporaryLayer = "TempCast";
  88. private int TemporaryLayerIndex;
  89. private float fixedDeltaTime;
  90.  
  91. public float speed = 26f;
  92. public float torque;
  93. public float maxVelocidade;
  94. public float velocidadeAtual;
  95. private float maxVelocity;
  96.  
  97. public float jumpSpeed = 8f;
  98. public float friction = 1f;
  99. private Vector3 currentVelocity = Vector3.zero;
  100. private float velocityY = 0f;
  101. private SuperCharacterController character;
  102.  
  103. public void Awake()
  104. {
  105. collisionData = new List<SuperCollision>();
  106.  
  107. TemporaryLayerIndex = LayerMask.NameToLayer(TemporaryLayer);
  108.  
  109. ignoredColliders = new List<Collider>();
  110. ignoredColliderStack = new List<IgnoredCollider>();
  111.  
  112. currentlyClampedTo = null;
  113.  
  114. fixedDeltaTime = 1.0f / fixedUpdatesPerSecond;
  115.  
  116. if (OwnCollider)
  117. IgnoreCollider(OwnCollider);
  118.  
  119. foreach (var sphere in spheres)
  120. {
  121. if (sphere.IsFeet)
  122. feet = sphere;
  123.  
  124. if (sphere.IsHead)
  125. head = sphere;
  126. }
  127.  
  128. if (feet == null)
  129. Debug.LogError("[SuperCharacterController] Feet not found on controller");
  130.  
  131. if (head == null)
  132. Debug.LogError("[SuperCharacterController] Head not found on controller");
  133.  
  134. gameObject.SendMessage("SuperStart", SendMessageOptions.DontRequireReceiver);
  135. }
  136.  
  137. void Start()
  138. {
  139. // maxVelocity = maxVelocidade * 3.6f;
  140. }
  141.  
  142. void Update()
  143. {
  144. // If we are using a fixed timestep, ensure we run the main update loop
  145. // a sufficient number of times based on the Time.deltaTime
  146.  
  147. if (!fixedTimeStep)
  148. {
  149. deltaTime = Time.deltaTime;
  150.  
  151. SingleUpdate();
  152. return;
  153. }
  154. else
  155. {
  156. float delta = Time.deltaTime;
  157.  
  158. while (delta > fixedDeltaTime)
  159. {
  160. deltaTime = fixedDeltaTime;
  161.  
  162. SingleUpdate();
  163.  
  164. delta -= fixedDeltaTime;
  165. }
  166.  
  167. if (delta > 0f)
  168. {
  169. deltaTime = delta;
  170.  
  171. SingleUpdate();
  172. }
  173. }
  174. if (!character)
  175. {
  176. // get the CharacterController only the first time:
  177. character = GetComponent<SuperCharacterController>();
  178. // get the direction from the controls:
  179. Vector3 dir = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
  180. // calculate the desired velocity:
  181. Vector3 vel = transform.TransformDirection(dir) * speed;
  182.  
  183. // here's where the magic happens:
  184. currentVelocity = Vector3.Lerp(currentVelocity, vel, friction * Time.deltaTime);
  185.  
  186. // apply gravity and jump after the friction!
  187. if(character.clamping)
  188. {
  189. velocityY = 0;
  190. }
  191. if (Input.GetButtonDown("Jump"))
  192. {
  193. velocityY = jumpSpeed;
  194. velocityY -= Time.deltaTime;
  195. currentVelocity.y = velocityY;
  196. currentVelocity = (currentVelocity * Time.deltaTime);
  197. }
  198. }
  199. }
  200.  
  201. private void OnTriggerStay(Collider other) {
  202.  
  203. if (other.gameObject.tag == "IceFloor")
  204. {
  205. Debug.Log("Gelo!");
  206.  
  207. if (Input.GetKey("w"))
  208. {
  209. float moveHorizontal = Input.GetAxis("Horizontal");
  210. float moveVertical = Input.GetAxis("Vertical");
  211.  
  212. Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
  213.  
  214. GetComponent<Collider>().material.dynamicFriction = 0.1f;
  215. GetComponent<Rigidbody>().AddForce(movement * speed * 2 * Time.deltaTime);
  216.  
  217. //Mathf.Clamp(GetComponent<Rigidbody>().velocity.x, 0, 3);
  218. //gameObject.GetComponent<Rigidbody>().velocity *= 0.99f;
  219.  
  220. //velocidadeAtual = Mathf.Abs(gameObject.GetComponent<Rigidbody>().velocity.sqrMagnitude / 3.6f);
  221.  
  222. }
  223. }
  224.  
  225. else if (other.gameObject.tag == "IceFloor")
  226. {
  227. Debug.Log("Gelo!");
  228.  
  229. if (Input.GetKey("s"))
  230. {
  231. float moveHorizontal = Input.GetAxis("Horizontal");
  232. float moveVertical = Input.GetAxis("Vertical");
  233.  
  234. Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
  235.  
  236. GetComponent<Collider>().material.dynamicFriction = 0.5f;
  237. GetComponent<Rigidbody>().AddForce(movement * speed / 2 * Time.deltaTime);
  238.  
  239. //gameObject.GetComponent<Rigidbody>().velocity *= 0.33f;
  240.  
  241. //velocidadeAtual = Mathf.Abs(gameObject.GetComponent<Rigidbody>().velocity.sqrMagnitude / 3.6f);
  242. }
  243. }
  244. }
  245.  
  246. public void antiUpwarp(){
  247. Walkable = 0;
  248. }
  249.  
  250. void SingleUpdate()
  251. {
  252. // Check if we are clamped to an object implicity or explicity
  253. bool isClamping = clamping || currentlyClampedTo != null;
  254. Transform clampedTo = currentlyClampedTo != null ? currentlyClampedTo : currentGround.Transform;
  255.  
  256. // Move our controller if clamped object moved in the previous frame
  257. if (isClamping && groundOffset != Vector3.zero && clampedTo != null)
  258. transform.position = clampedTo.position + groundOffset;
  259.  
  260. initialPosition = transform.position;
  261.  
  262. ProbeGroundRecursive();
  263.  
  264. transform.position += debugMove * deltaTime;
  265.  
  266. gameObject.SendMessage("SuperUpdate", SendMessageOptions.DontRequireReceiver);
  267.  
  268. Pushback();
  269.  
  270. ProbeGroundRecursive();
  271.  
  272. if (slopeLimiting)
  273. SlopeLimit();
  274.  
  275. ProbeGroundRecursive();
  276.  
  277. if (clamping)
  278. ClampToGround();
  279.  
  280. isClamping = clamping || currentlyClampedTo != null;
  281. clampedTo = currentlyClampedTo != null ? currentlyClampedTo : currentGround.Transform;
  282.  
  283. if (isClamping)
  284. groundOffset = transform.position - clampedTo.position;
  285.  
  286. }
  287.  
  288. /// <summary>
  289. /// Prevents the player from walking up slopes of a larger angle than the object's SlopeLimit.
  290. /// NOTE: Since ProbeGroundRecursive ignores any slopes greater than StandAngle, the controller
  291. /// will not be slope limited against these slopes.
  292. /// </summary>
  293. /// <returns>True if the controller attemped to ascend a too steep slope and had their movement limited</returns>
  294. bool SlopeLimit()
  295. {
  296. Vector3 n = currentGround.Hit.normal;
  297. float a = Vector3.Angle(n, up);
  298.  
  299. if (a > currentGround.CollisionType.SlopeLimit)
  300. {
  301. Vector3 absoluteMoveDirection = Math3d.ProjectVectorOnPlane(n, transform.position - initialPosition);
  302.  
  303. // Retrieve a vector pointing down the slope
  304. Vector3 r = Vector3.Cross(n, down);
  305. Vector3 v = Vector3.Cross(r, n);
  306.  
  307. float angle = Vector3.Angle(absoluteMoveDirection, v);
  308.  
  309. if (angle <= 90.0f)
  310. return false;
  311.  
  312. // Calculate where to place the controller on the slope, or at the bottom, based on the desired movement distance
  313. Vector3 resolvedPosition = Math3d.ProjectPointOnLine(initialPosition, r, transform.position);
  314. Vector3 direction = Math3d.ProjectVectorOnPlane(n, resolvedPosition - transform.position);
  315.  
  316. RaycastHit hit;
  317.  
  318. // Check if our path to our resolved position is blocked by any colliders
  319. if (Physics.CapsuleCast(OffsetPosition(feet.Offset), OffsetPosition(head.Offset), radius, direction.normalized, out hit, direction.magnitude, Walkable))
  320. {
  321. transform.position += v.normalized * hit.distance;
  322. }
  323. else
  324. {
  325. transform.position += direction;
  326. }
  327.  
  328. return true;
  329. }
  330.  
  331. return false;
  332. }
  333.  
  334. void ClampToGround()
  335. {
  336. float d = currentGround.Hit.distance;
  337. transform.position -= up * d;
  338. }
  339.  
  340. public void EnableClamping()
  341. {
  342. clamping = true;
  343. }
  344.  
  345. public void DisableClamping()
  346. {
  347. clamping = false;
  348. }
  349.  
  350. public void EnableSlopeLimit()
  351. {
  352. slopeLimiting = true;
  353. }
  354.  
  355. public void DisableSlopeLimit()
  356. {
  357. slopeLimiting = false;
  358. }
  359.  
  360. public bool IsClamping()
  361. {
  362. return clamping;
  363. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement