Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- /// <summary>
- /// Character motor for fps player.
- /// </summary>
- [AddComponentMenu("FPS Stuff/Player Movement")]
- public class PlayerMovement : MonoBehaviour
- {
- public float movementSpeed = 10;
- public float speedMultiplier = 1;
- public float maxVelocityChange = 10;
- public float jumpHeight = 2;
- public bool canJump = true;
- public bool grounded = false;
- void FixedUpdate()
- {
- if (grounded)
- {
- float h = Input.GetAxis("Horizontal") * movementSpeed * speedMultiplier * 0.7f;
- float v = Input.GetAxis("Vertical") * movementSpeed * speedMultiplier;
- Vector3 targetVelocity = transform.TransformDirection(new Vector3(h, 0, v));
- Vector3 velocityChange = (targetVelocity - rigidbody.velocity);
- velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
- velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
- velocityChange.y = 0;
- rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
- // Jump
- if (canJump && Input.GetButton("Jump"))
- {
- rigidbody.velocity = new Vector3(rigidbody.velocity.x, CalculateJumpVerticalSpeed(), rigidbody.velocity.z);
- }
- }
- grounded = false;
- }
- void OnCollisionStay()
- {
- grounded = true;
- }
- float CalculateJumpVerticalSpeed()
- {
- // From the jump height and gravity we deduce the upwards speed
- // for the character to reach at the apex.
- return Mathf.Sqrt(2 * jumpHeight * -Physics.gravity.y);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement