unity CharacterMotor 中按下shift 实现加速

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

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

  • using UnityEngine;
  • using System.Collections;
  • public class RunAndCrouch : MonoBehaviour
  • {
  • public float walkSpeed = 7; // regular speed
  • public float crchSpeed = 3; // crouching speed
  • public float runSpeed = 20; // run speed
  • private CharacterMotor chMotor;
  • private Transform tr;
  • private float dist; // distance to ground
  • // Use this for initialization
  • void Start ()
  • {
  • chMotor = GetComponent<CharacterMotor>();
  • tr = transform;
  • CharacterController ch = GetComponent<CharacterController>();
  • dist = ch.height/2; // calculate distance to ground
  • }
  • // Update is called once per frame
  • void FixedUpdate ()
  • {
  • float vScale = 1.0f;
  • float speed = 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
  • float ultScale = tr.localScale.y; // crouch/stand up smoothly
  • Vector3 tmpScale = tr.localScale;
  • Vector3 tmpPosition = 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;
  • }
  • }


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部