刚体控制的角色在上坡时移动非常奇怪
Posted
技术标签:
【中文标题】刚体控制的角色在上坡时移动非常奇怪【英文标题】:Rigidbody controlled character moves very strangely when going up slopes 【发布时间】:2022-01-13 22:05:28 【问题描述】:我正在为 Unity 中基于物理的第一人称角色控制器编写代码。移动大部分是平稳的,但是当我上坡时,角色并没有滑下来,而是稍微漂浮在空中,同时缓慢地向下移动,直到它回到地面。这种行为非常奇怪和出乎意料,我真的不知道为什么会这样。
角色是一个空对象,带有一个胶囊和一个球体。脚本在空对象上,刚体在胶囊上,胶囊是空的孩子。 这是脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
float mouseSensitivity;
private float cameraXRotation;
private float cameraYRotation;
private float movementX;
private float movementY;
private Transform playerHeadTransform;
private Transform playerBodyTransform;
private Rigidbody playerRigidBody;
private bool IsJumping;
// Start is called before the first frame update
void Start()
Cursor.lockState = CursorLockMode.Locked;
playerBodyTransform = transform.GetChild(0).gameObject.GetComponent<Transform>();
playerHeadTransform = transform.GetChild(0).transform.GetChild(0).gameObject.GetComponent<Transform>();
playerRigidBody = transform.GetChild(0).gameObject.GetComponent<Rigidbody>();
playerHeadTransform.transform.rotation = Quaternion.Euler(0f, 0f, 0f);
mouseSensitivity = 750;
IsJumping = false;
// Update is called once per frame
void Update()
#region CameraStuff
float cameraMouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float cameraMouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
cameraXRotation -= cameraMouseY;
cameraYRotation += cameraMouseX;
cameraXRotation = Mathf.Clamp(cameraXRotation, -90f, 60);
playerHeadTransform.localRotation = Quaternion.Euler(cameraXRotation, 0f, 0f);
playerBodyTransform.localRotation = Quaternion.Euler(0f, cameraYRotation, 0f);
#endregion
//Movement input variables
movementX = Input.GetAxis("Horizontal") * mouseSensitivity * Time.deltaTime;
movementY = Input.GetAxis("Vertical") * mouseSensitivity * Time.deltaTime;
void FixedUpdate()
playerRigidBody.velocity = playerBodyTransform.TransformDirection(movementX*2, 0, movementY*2);
【问题讨论】:
就像一个非常一般的提示:GetChild(0)
已经返回了一个Transform
,所以通过gameObject.GetComponent<Transform>()
是完全多余的;) 通常GetComponent<Transform>()
是多余的,因为每个Component
和@ 987654327@ 已经有一个属性.transform
;)
【参考方案1】:
您的播放器没有摔倒很可能与您的设置有关
void FixedUpdate()
playerRigidBody.velocity = playerBodyTransform.TransformDirection(movementX*2, 0, movementY*2);
如果涉及重力,您宁愿确保不覆盖 Y
轴并执行例如
var currentVelocity = playerRigidbody.velocity;
var newVelocity = playerBodyTransform.TransformDirection(movementX * 2, 0, movementY * 2);
// keep the velocity on Y but only if it is currently downwards
// so you can still move up on a slope but fall down with gravity
if(currentVelocity.y < 0) newVelocity.y = currentVelocity.y;
playerRigidBody.velocity = newVelocity;
【讨论】:
以上是关于刚体控制的角色在上坡时移动非常奇怪的主要内容,如果未能解决你的问题,请参考以下文章