根据《行动中的团结》一书,我学习了第7章,我不知道我是在做错什么还是在书中犯了错误。通常,角色控制器会紧贴对象,结果漂浮在空中,因为它是一个胶囊对撞机,但是模型本身已不在设施中。这是我试图通过抛出光束来解决的方法
public class Walk : MonoBehaviour
{
[SerializeField] private Transform target;
public float moveSpeed = 6.0f;
public float rotSpeed = 15.0f;
public float jumpSpeed = 15.0f;
public float gravity = -9.8f;
public float terminalVelocity = -20.0f;
public float minFall = -1.5f;
private float _vertSpeed;
private ControllerColliderHit _contact;
private CharacterController _charController;
void Start()
{
_vertSpeed = minFall;
_charController = GetComponent<CharacterController>();
}
void Update()
{
Vector3 movement = Vector3.zero;
float horInput = Input.GetAxis("Horizontal");
float vertInput = Input.GetAxis("Vertical");
if (horInput != 0 || vertInput != 0)
{
movement.x = horInput * moveSpeed;
movement.z = vertInput * moveSpeed;
movement = Vector3.ClampMagnitude(movement, moveSpeed);
Quaternion tmp = target.rotation;
target.eulerAngles = new Vector3(0, target.eulerAngles.y, 0);
movement = target.TransformDirection(movement);
target.rotation = tmp;
Quaternion direction = Quaternion.LookRotation(movement);
transform.rotation = Quaternion.Lerp(transform.rotation,
direction, rotSpeed * Time.deltaTime);
}
bool hitGround = false;
RaycastHit hit;
if (_vertSpeed < 0 && Physics.Raycast(transform.position, Vector3.down, out hit))
{
float check = (_charController.height + _charController.radius) / 1.9f;
hitGround = hit.distance <= check;
}
if (hitGround)
{
if (Input.GetButtonDown("Jump"))
{
_vertSpeed = jumpSpeed;
}
else
{
_vertSpeed = minFall;
}
}
else
{
_vertSpeed += gravity * 5 * Time.deltaTime;
if (_vertSpeed < terminalVelocity)
{
_vertSpeed = terminalVelocity;
}
if (_charController.isGrounded)
{
if (Vector3.Dot(movement, _contact.normal) < 0)
{
movement = _contact.normal * moveSpeed;
}
else
{
movement += _contact.normal * moveSpeed;
}
}
}
movement.y = _vertSpeed;
movement *= Time.deltaTime;
_charController.Move(movement);
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
_contact = hit;
}
}