unity通用角色控制脚本【走.跑.跳.下蹲】
时间: 2023-06-13 19:03:46 浏览: 66
以下是一个基本的Unity角色控制脚本,包含走、跑、跳和下蹲功能:
```csharp
using UnityEngine;
public class CharacterController : MonoBehaviour
{
public float walkSpeed = 5.0f;
public float runSpeed = 10.0f;
public float jumpForce = 10.0f;
public float gravity = 20.0f;
public float crouchSpeed = 2.5f;
public float crouchHeight = 0.5f;
public float standingHeight = 2.0f;
private CharacterController controller;
private Vector3 moveDirection = Vector3.zero;
private float verticalVelocity = 0.0f;
private bool isCrouching = false;
void Start()
{
controller = GetComponent<CharacterController>();
controller.height = standingHeight;
}
void Update()
{
// Get input from player
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
bool run = Input.GetKey(KeyCode.LeftShift);
bool jump = Input.GetKeyDown(KeyCode.Space);
bool crouch = Input.GetKeyDown(KeyCode.LeftControl);
// Calculate movement direction and speed
Vector3 move = transform.right * horizontal + transform.forward * vertical;
moveDirection = Vector3.ClampMagnitude(move, 1.0f);
float speed = run ? runSpeed : walkSpeed;
// Apply gravity
if (controller.isGrounded)
{
verticalVelocity = 0.0f;
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
// Apply jump force
if (jump && controller.isGrounded)
{
verticalVelocity = jumpForce;
}
// Apply crouch
if (crouch && !isCrouching)
{
controller.height = crouchHeight;
speed = crouchSpeed;
isCrouching = true;
}
else if (!crouch && isCrouching)
{
// Check if there is enough space to stand up
if (!Physics.SphereCast(transform.position, controller.radius, Vector3.up, standingHeight - crouchHeight))
{
controller.height = standingHeight;
speed = run ? runSpeed : walkSpeed;
isCrouching = false;
}
}
// Move the character
moveDirection *= speed;
moveDirection.y = verticalVelocity;
controller.Move(moveDirection * Time.deltaTime);
}
}
```
这个脚本需要附加到您的角色对象上,并且需要在 Unity 中进行设置,以便将正确的值分配给 `walkSpeed`、`runSpeed`、`jumpForce`、`gravity`、`crouchSpeed`、`crouchHeight` 和 `standingHeight` 变量。