unity CharacterMotor 中按下shift 实现加速

按下shift加速,减速,实际上只是速度的变换。刚开始,我直接在CharacterMotor中修改代码,结果出现一些很奇怪的问题。后来在http://answers.unity3d.com/questions/164638/how-to-make-the-fps-character-controller-run-and-c.html

找到了解决方法。从新写一个脚本,

  • usingUnityEngine;
  • usingSystem.Collections;
  • publicclassRunAndCrouch:MonoBehaviour
  • {
  • publicfloatwalkSpeed=7;// regular speed
  • publicfloatcrchSpeed=3;// crouching speed
  • publicfloatrunSpeed=20;// run speed
  • privateCharacterMotorchMotor;
  • privateTransformtr;
  • privatefloatdist;// distance to ground
  • // Use this for initialization
  • voidStart()
  • {
  • chMotor=GetComponent<CharacterMotor>();
  • tr=transform;
  • CharacterControllerch=GetComponent<CharacterController>();
  • dist=ch.height/2;// calculate distance to ground
  • }
  • // Update is called once per frame
  • voidFixedUpdate()
  • {
  • floatvScale=1.0f;
  • floatspeed=walkSpeed;
  • if((Input.GetKey("left shift")||Input.GetKey("right shift"))&&chMotor.grounded)
  • {
  • speed=runSpeed;
  • }
  • if(Input.GetKey("c"))
  • {// press C to crouch
  • vScale=0.5f;
  • speed=crchSpeed;// slow down when crouching
  • }
  • chMotor.movement.maxForwardSpeed=speed;// set max speed
  • floatultScale=tr.localScale.y;// crouch/stand up smoothly
  • Vector3tmpScale=tr.localScale;
  • Vector3tmpPosition=tr.position;
  • tmpScale.y=Mathf.Lerp(tr.localScale.y,vScale,5*Time.deltaTime);
  • tr.localScale=tmpScale;
  • tmpPosition.y+=dist*(tr.localScale.y-ultScale);// fix vertical position
  • tr.position=tmpPosition;
  • }
  • }


版权声明:本文为naoomi原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。