【发布时间】:2021-05-14 16:53:09
【问题描述】:
您好,我正在尝试为 fps 游戏创建运动脚本。我有运动但跳转功能不起作用我不确定问题是代码还是我设置字符的方式。在调试日志中,它正在注册我按下了空格键,在调试中它说:FixedUpdate Jump UnityEngine.Debug:Log (object) PlayerMovement:FixedUpdate () (at Assets/PlayerMovement.cs:94)
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
private float _speed = 7f;
private CharacterController _charController;
private float _mouseSensitivity = 450;
private Camera _camera;
private float xRotation = 0f;
private float _minCameraview = -70f, _maxCameraview = 90f;
private Vector3 _PlayerVelocity;
public Vector3 jump;
public float jumpForce = 2.0f;
bool isJumpPressed = false;
public bool isGrounded = true;
Rigidbody rb;
// Start is called before the first frame update
void Start()
{
_charController = GetComponent<CharacterController>();
_camera = Camera.main;
Cursor.lockState = CursorLockMode.Locked;
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 2.0f, 0.0f);
//if(_charController == null)
//Debug.log("No Character Controller attached to player");
}
// Update is called once per frame
void Update()
{
//Get WASD input for player
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
// Move player based on WASD input
Vector3 movement = transform.forward * vertical + transform.right * horizontal;
_charController.Move(movement * Time.deltaTime * _speed);
//Get mouse position input
float mouseX = Input.GetAxis("Mouse X") * _mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * _mouseSensitivity * Time.deltaTime;
// rotate camera based off Y input from Mouse
xRotation -= mouseY;
// Clamp Camera rotation
xRotation = Mathf.Clamp(xRotation, _minCameraview, _maxCameraview);
_camera.transform.localRotation = Quaternion.Euler(xRotation, 0, 0);
// rotate player based off X input from Mouse
transform.Rotate(Vector3.up * mouseX * 3);
//Jumping
if(Input.GetKeyDown(KeyCode.Space) && isGrounded){
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
isJumpPressed = Input.GetKeyDown(KeyCode.Space);
if (isJumpPressed)
{
Debug.Log("Update Jump");
}
}
void FixedUpdate()
{
// dectect if player is grounded
if (_charController.isGrounded)
{
_PlayerVelocity.y = 0f;
}
// apply gravity to player
else
{
_PlayerVelocity.y += -9.18f * Time.deltaTime;
_charController.Move(_PlayerVelocity * Time.deltaTime);
}
if (isJumpPressed)
{
Debug.Log("FixedUpdate Jump");
}
}
}
Rigidbody 我也在使用刚接触的 Rigidbody3D,所以这里是它的设置方式。
这里是角色控制器Character Controller
这是统一的玩家运动PlayerMovement
那么我做错了什么,所以我的角色不会跳?如果可能的话,你能解释一下吗,因为我也试图理解它背后的概念。 (如果这很重要,我正在使用 unity 2020.2.2f1。)
【问题讨论】:
-
如果你说你使用的是刚体和 CharacterController,那肯定是问题所在。你永远不应该两者兼得。没有其他方法,总有办法做到这一点。
-
如果你想用角色控制器跳跃,我有一个简单的脚本给你。如果您愿意,请告诉我。
-
@ken 那么你将如何只使用刚体呢?如果你能把角色控制器的脚本也发给我,那就太好了,因为我也想学习。
-
字符控制器在这种情况下是更好的选择。我会在答案中解释。
标签: c# visual-studio unity3d