Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class Player : MonoBehaviour {
- // place on cube, add a rigidbody, with Freeze Position Z, and Freeze Rotation X,Y,Z
- // use new physic material with zeroed frictions, and friction combine: minimum.
- public float moveSpeed = 8;
- public float jumpSpeed = 25;
- public float fallSpeed = 64;
- public float maxFallSpeed = 12;
- public float maxUpSpeed = 25;
- Vector3 pos;
- float vm;
- bool onGround;
- // Update is called once per frame
- void FixedUpdate () {
- pos = transform.position;
- float h = Input.GetAxisRaw("Horizontal");
- float v = Input.GetAxisRaw("Vertical");
- bool jump = Input.GetKey(KeyCode.Space);
- if (onGround && jump)
- {
- vm = jumpSpeed;
- }
- Vector3 move = new Vector3( -h*moveSpeed, vm, 0 ) * Time.deltaTime;
- rigidbody.MovePosition( pos + move );
- if (v > 0)
- {
- // jet pack!
- vm += v * Time.deltaTime * 20;
- } else {
- // gravity
- vm -= fallSpeed * Time.deltaTime;
- }
- vm = Mathf.Clamp(vm,-maxFallSpeed,maxUpSpeed);
- rigidbody.velocity = Vector3.zero;
- onGround = false;
- }
- // ---- Collisions ----
- void OnCollisionEnter(Collision c) {
- CheckCollision (c);
- }
- void OnCollisionStay(Collision c)
- {
- CheckCollision(c);
- }
- void CheckCollision (Collision c)
- {
- foreach (var contact in c.contacts)
- {
- Debug.DrawLine(contact.point, contact.point+contact.normal, Color.red);
- // check for floor hit
- if (vm <= 0 && contact.point.y <= collider.bounds.min.y && Vector3.Angle(Vector3.up,contact.normal)<=45)
- {
- onGround = true;
- vm = Mathf.Max(0,vm);
- }
- // check for head hit:
- if (contact.point.y >= collider.bounds.max.y && Vector3.Angle(-Vector3.up,contact.normal)<=45)
- {
- vm = Mathf.Min(0,vm);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment