【发布时间】:2021-08-18 17:56:46
【问题描述】:
我对 c#、统一和编码非常陌生。我正在尝试制作一个可以蹲下、跳跃和冲刺的可控 3d 角色。由于我在标题中所描述的,Sprinting 目前不起作用:玩家的速度在统一检查器中更新,但实际上并没有在游戏中改变。
完整的玩家移动脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float gravity = -9.807f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float jumpHeight = 3f;
public float crouchHeight = 0.9f;
public float playerPushPower = 2.0f;
public float speed = 16f;
public float sprintSpeed = 1.5f;
public float crouchSpeed = 0.5f;
private float baseSpeed = 16f;
bool isGrounded;
bool isSprinting = false;
bool isCrouching = false;
bool isJumping = false;
bool isStanding = true;
Vector3 velocity;
void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
playerPushPower = speed / 8;
// no rigidbody
if (body == null || body.isKinematic)
return;
// We dont want to push objects below us
if (hit.moveDirection.y < -0.3f)
return;
// Calculate push direction from move direction,
// we only push objects to the sides never up and down
Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
// If you know how fast your character is trying to move,
// then you can also multiply the push velocity by that.
// Apply the push
body.velocity = pushDir * playerPushPower;
}
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
controller.height = 3.8f;
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
if(Input.GetKey("left ctrl") && isGrounded)
{
speed = speed * crouchSpeed;
isCrouching = true;
isStanding = false;
}
else
{
speed = 16f;
isCrouching = false;
isStanding = true;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded && isStanding)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
isJumping = true;
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
if(Input.GetKey("left shift") && isGrounded && isStanding)
{
speed = speed * sprintSpeed;
isSprinting = true;
}
else
{
speed = 16f;
isSprinting = false;
}
}
}
【问题讨论】: