Unity 3 DはFirstPersonControllerにランニングとスクワット動作を追加

6621 ワード

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 }