Unity3D为FirstPersonController添加跑步与下蹲动作

using UnityEngine; using System.Collections; public class MyController : MonoBehaviour { public float walkSpeed = 7; public float crouchSpeed = 3; public float runSpeed = 20; private CharacterMotor motor; private float dist;//distance to ground // Use this for initialization

    void Start () { motor = GetComponent<CharacterMotor>(); CharacterController ch = GetComponent<CharacterController>(); dist = ch.height / 2; } void FixedUpdate() { float vScale = 1.0f; float speed = walkSpeed; if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && 
       Input.GetKey(KeyCode.W)) { speed
= runSpeed; } if (Input.GetKey(KeyCode.C)) { vScale = 0.5f; speed = crouchSpeed; } motor.movement.maxForwardSpeed = speed;//set max speed float ultScale = transform.localScale.y;//crouch stand up smoothly Vector3 tmpScale = transform.localScale; Vector3 tmpPosition = transform.position; tmpScale.y = Mathf.Lerp(transform.localScale.y, vScale, 5 * Time.deltaTime); transform.localScale = tmpScale; tmpPosition.y += dist * (transform.localScale.y - ultScale);//fix vertical position transform.position = tmpPosition; } }

本文转自其它网站。添加了First Person Controller后,直接挂上代码即可实现跑步与下蹲。下面是相应的JavaScript代码:

var walkSpeed: float = 7; // regular speed

var crchSpeed: float = 3; // crouching speed

var runSpeed: float = 20; // run speed

 private var chMotor: CharacterMotor; private var ch: CharacterController; private var tr: Transform; private var height: float; // initial height

 

function Start(){ chMotor = GetComponent(CharacterMotor); tr = transform; ch = GetComponent(CharacterController); height = ch.height; } function Update(){ var h = height; var speed = walkSpeed; if (ch.isGrounded && Input.GetKey("left shift") || Input.GetKey("right shift")){ speed = runSpeed; } if (Input.GetKey("c")){ // press C to crouch

        h = 0.5 * height; speed = crchSpeed; // slow down when crouching

 } chMotor.movement.maxForwardSpeed = speed; // set max speed

    var lastHeight = ch.height; // crouch/stand up smoothly 

    ch.height = Mathf.Lerp(ch.height, h, 5*Time.deltaTime); tr.position.y += (ch.height-lastHeight)/2; // fix vertical position }

 

 

 

你可能感兴趣的:(controller)