【发布时间】:2021-11-21 06:15:10
【问题描述】:
如果按住空格键直到你松开,我的角色会一直漂浮,我整天都在尝试如何让角色正常跳跃,但我只是卡住了。我正在使用统一来创建游戏。当我更改 onfloor=true 时,问题就开始了,在它为 false 之前,角色只能跳一次。这是C#中字符的代码
谢谢
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Transform rotateBody;
private Vector3 Direction;
private const float gravity = 0.1f;
private const float jump_force = 0.09f;
public Transform groundCheckTransform;
private bool shiftKeyWasPressed;
private bool jumpKeyWasPressed;
private float horizontalInput;
private Rigidbody RigidbodyComponent;
public LayerMask playerMask;
private int superJumpsRemaing;
private bool on_floor = true;
// Start is called before the first frame update
void Start()
{
RigidbodyComponent = GetComponent<Rigidbody>();
shiftKeyWasPressed = false;
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space) & Direction.y > 0){
jumpKeyWasPressed = true;
}
horizontalInput = Input.GetAxis("Horizontal");
if(Input.GetKeyDown(KeyCode.LeftShift)){
shiftKeyWasPressed = true;
}
horizontalInput = Input.GetAxis("Horizontal");
}
void FixedUpdate(){
Direction.y -= gravity;
Direction.x = 0;
if (Input.GetKey(KeyCode.Space)){
if (Direction.y < 0 && on_floor){
Direction.y = 0;
}
if(on_floor){
Direction.y += jump_force*2;
on_floor = true;
}
}else{
jumpKeyWasPressed = false;
}
if (Input.GetKey(KeyCode.D)){
Direction.x += 2;
}
if (Input.GetKey(KeyCode.A)){
Direction.x -= 2;
}
if (Input.GetKey(KeyCode.LeftShift))
if(shiftKeyWasPressed==true)
Direction.x *= 6;
if(Physics.OverlapSphere(groundCheckTransform.position, 0.1f, playerMask).Length == 0){
return;
}
if (jumpKeyWasPressed)
{
float jumpPower = 7;
if (superJumpsRemaing > 0){
jumpPower *=2;
superJumpsRemaing--;
}
RigidbodyComponent.AddForce(Vector3.up*jumpPower, ForceMode.VelocityChange);
jumpKeyWasPressed = false;
}
RigidbodyComponent.velocity = Direction;
}
private void OnTriggerEnter(Collider other)
{
if ( other.gameObject.layer == 8){
jumpKeyWasPressed = true;
if(Direction.y > 8)
jumpKeyWasPressed = false;
}
if (other.gameObject.layer == 6){
Destroy(other.gameObject);
}
if (other.gameObject.layer == 7){
Destroy(other.gameObject);
superJumpsRemaing++;
}
}
}
【问题讨论】: