12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using System;
- using UnityEngine;
- namespace Comp
- {
- public class CockMoveComp : MonoBehaviour
- {
- // 刚体
- private Rigidbody _rigidbody;
- // 水平运动相关
- private bool _isMoving; // 是否进行水平运动
- private float _movingTime; // 水平运动时间
- private const float MovingSpeed = 1f; // 移动速度
- private const float MovingTime = 1f; // 移动时间
- // 跳跃相关
- private const float HighJumpSpeed = 2f; // 高跳速度
- private const float LowJumpSpeed = 1f; // 低跳速度
- private Vector3 CreateMovingVector(float speed)
- {
- var forward = transform.forward;
- return new Vector3(speed * forward.x, 0, 0);
- }
- private Vector3 CreateJumpingVector(float y)
- {
- return new Vector3(0, y, 0);
- }
- public void Move()
- {
- _isMoving = true;
- _movingTime = MovingTime;
- }
- public void MoveAndNeverStop()
- {
- _isMoving = true;
- _movingTime = float.MaxValue;
- }
- public void Stop()
- {
- _isMoving = false;
- _movingTime = 0;
- }
- public void Jump(bool highJump)
- {
- var jumpSpeed = highJump ? HighJumpSpeed : LowJumpSpeed;
- var jumpingVector = CreateJumpingVector(jumpSpeed);
- _rigidbody.AddForce(jumpingVector); // 添加力
- }
- private void Start()
- {
- _rigidbody = GetComponent<Rigidbody>();
- }
- private void FixedUpdate()
- {
- if (!_isMoving) return;
- var movingVector = CreateMovingVector(MovingSpeed);
- transform.position += movingVector * Time.deltaTime;
- _movingTime -= Time.deltaTime;
- if (_movingTime <= 0)
- _isMoving = false;
- }
- }
- }
|