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;
  • }
  • }

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值